我想实现一个自定义注释,当它被其他类使用时,会向它们公开两个方法。如下所示:
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface BaseEntity{
public String toString(){ return "Hello" ;}
public String toCustomString() { return "my hello";}
}现在我想要的是当任何类使用上面的注解时。默认情况下,它将这些方法公开给它,就像我们使用@Getter时Lombok所做的那样
@BaseEntity
public class Person{}
Person p = new Person();
p.toCustomString(); // this should work发布于 2020-06-27 02:23:31
您需要创建一个批注处理类(必须是javax.annotation.processing.AbstractProcessor的子类)才能将代码实际添加到Person类中。
请参阅:http://hannesdorfmann.com/annotation-processing/annotationprocessing101
发布于 2020-06-27 03:28:14
虽然不完全符合您的要求,但我认为您可以使用利用注释的类层次结构来实现您想要的结果:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface BaseEntity {
String string();
String customString();
}
public abstract class AbstractClass {
@Override
public String toString() {
return getClass().getAnnotation(BaseEntity.class).string();
}
public String toCustomString() {
return getClass().getAnnotation(BaseEntity.class).customString();
}
}然后是一个具体的子类:
@BaseEntity(string = "Hello", customString = "my hello")
public class Example extends AbstractClass {
public static void main(String[] args) throws Exception {
Example example = new Example();
System.out.println(example.toString());
System.out.println(example.toCustomString());
}
}收益率:
Hello
my hello为了回应您的评论,我的实际解决方案是使用默认方法定义一个注释和一个接口(这会使toString()实现出现问题):
@BaseEntity(customString = "my hello")
public class Example implements BaseEntityAnnotated {
public static void main(String[] args) throws Exception {
Example example = new Example();
System.out.println(example.toCustomString());
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface BaseEntity {
String customString();
}
public interface BaseEntityAnnotated {
default String toCustomString() {
return this.getClass().getAnnotation(BaseEntity.class).customString();
}
}然后,我实现了一个Processor,它强制使用BaseEntity注释的实体也必须实现BaseEntityAnnotated。
我在AntTask、AnnotatedAntTask.getAntTaskName()和AntTaskProcessor都有这样的例子。
https://stackoverflow.com/questions/62599910
复制相似问题