我有一个使用注释的 Java 类。我想编写一个版本来扩展它并更改现有方法的注释。
所以会有一个方法具有:
@myAnnotation(value=VALUE_THAT_CHANGE_IN_SUBCLASS)
myMethod(){
}
子类将有几个新方法,但主要只是按照我所说的方式更改注释。
最佳答案
虽然我不确定您为什么想要这样做,但您需要扩展类、重写方法并应用注释:
public class App
{
public static void main(String[] args) throws NoSuchMethodException
{
Class<MyClass> c = MyClass.class;
MyAnnotation a = c.getMethod("someMethod",null).getAnnotation(MyAnnotation.class);
System.out.println(a.name());
Class<MySubclass> c2 = MySubclass.class;
a = c2.getMethod("someMethod",null).getAnnotation(MyAnnotation.class);
System.out.println(a.name());
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
String name() default "";
}
class MyClass {
@MyAnnotation(name="Some value")
public String someMethod() {
return "Hi!";
}
}
class MySubclass extends MyClass {
@Override
@MyAnnotation(name="Some other value")
public String someMethod() {
return super.someMethod();
}
}
输出:
Some value
Some other value
关于java - 如何扩展 Java 类并更改注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840893/