Java Lombok Project is just an awesome stuff. It provides a possibility to get rid of tons of generated getters / setters and use simple, comprehensible annotations.

But for my automation project I should return interface of some element. Is it possible for lombok to return interface of an object?

For example, I have:

private ButtonElement button = new ButtonElement(....);
public IElement getButton() {
     return button;
}  

and would like to have something like:

@Getter   // with with IElement return type?   
private ButtonElement button = new ButtonElement(....); 
有帮助吗?

解决方案

Yes but it's clumsy:

@Getter
private IElement button = new ButtonElement(....);

But that will of course make it harder to access some methods of ButtonElement. So you may want to use either:

private _button = new ButtonElement(....);
@Getter
private IElement button = _button;

i.e. you need two fields, one with the interface and one with the real type.

or

@Getter
private IElement button = new ButtonElement(....);
private ButtonElement button() { return (ButtonElement) button; }

i.e. you now have an internal getter which casts and returns the real type.

Note that Java allows you to define a method which expands the type. So if you have an interface which says:

IElement getButton();

you can implement this with

public ButtonElement getButton() {...}

Not only will this work but if Java knows which getButton() you're calling, it will happily give you a ButtonElement.

其他提示

If you define the field type as the interface, it will of course return the interface, otherwise, I think there's no way.

I would simply change your code to

@Getter      
private IElement button = new ButtonElement(....); 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top