简体   繁体   中英

How to read the implementation class in default interface method?

I want to create a default interface method that can respond with the annotated value of the implementation class.

Example: in the following, I want all Child implementations to read their own @Generated value field:

public interface Parent {
    default String[] find() {
        return AnnotationUtils.findAnnotation(this.getClass(), Generated.class).value();
    }
}

@Generated(value = {"test"})
public class Child implements Parent {

}

Usage:

System.out.println(new Child().find());

Result: NullPointerException , because the call tries to find the annotation on the Parent interface class, not the implementation class.

It it still possible somehow?

Your question is based on a false premise. this.getClass() does not return Parent

Assuming your @Generated annotation is the javax version , you are getting a NPE because it is not retained at runtime.

See @Retention

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