【问题标题】:How do you extend a Java class and change annotations?如何扩展 Java 类并更改注解?
【发布时间】:2013-02-12 20:09:14
【问题描述】:

我有一个使用注解的 Java 类。我想编写一个扩展它并更改现有方法的注释的版本。

所以会有一个方法:

@myAnnotation(value=VALUE_THAT_CHANGE_IN_SUBCLASS)
    myMethod(){
}

子类将有几个新方法,但大多只是按照我所说的方式更改注释。

【问题讨论】:

标签: java inheritance annotations


【解决方案1】:

虽然我不确定您为什么要这样做,但您需要扩展类、覆盖方法并应用注释:

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();
    }
}

输出:

一些价值
其他一些价值

【讨论】:

  • 这样的过程是否也可以应用于字段注释(或者我应该问一个新问题)?
猜你喜欢
  • 2014-04-03
  • 2014-01-22
  • 2011-04-14
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多