简体   繁体   中英

Why doesn't lombok provide a getter method for inherited attribute?

Given that i have the below class

import lombok.Data;
@Data
public class A extends B {
}

And then class B is as below:

@Data
public class B {
    protected Driver driver;
}

But, when i try to get the driver by the following code:

A a = new A();
a.getDriver();

But it complains with:

The method getDriver() is undefined for the type A

Because driver is protected and Data all generated getters and setters will be public (according to documentation). It is trying to access higher level privileges. Try:

 import lombok.AccessLevel;
 @Getter(AccessLevel.PROTECTED) protected Driver driver;

Try specifying the AccessLevel on the driver field:

@Getter(AccessLevel.PROTECTED)
protected Driver driver;

You can read more about the AccessLevel here in the documentation: https://projectlombok.org/api/lombok/AccessLevel.html

I don't know how the other answer got accepted and even less how amer's answer got 7 upvotes when they do not answer the question at all.

Using lombok's @Getter annotation and setting AccessLevel of field to protected does exactly what it says on the tin - it sets the AccessLevel of field's getter to protected. That means it's not visible from the outside of the class, or classes that inherit that very same class.

The real answer is that yes - you've pointed it out correctly - lombok does not provide getter methods for inherited fields. This was proposed as a feature here , but was not implemented.

As to why, resolution was linked on that same issue. To quote:

Basically we can't do it! We can't ask these questions in lombok. The problem is: The answers to these questions are not available until the compiler is much further along the compilation process: It has a list of all types on the source and class path and then for each such type, what it extends/implements, what its members are, etc. That's the key point: Lombok wants to modify this list: Lombok generates new methods. If the list of all methods of all types is already made, lombok is too late!

For all these features it's chicken-and-egg: If we wait until the compilation process has gone on far enough that we do resolution, it's too late to add an equals and hashCode method to the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM