2013-02-12 49 views
1

我有一個使用註釋的Java類。我想編寫一個擴展它的版本並更改現有方法的註釋。如何擴展Java類並更改註釋?

所以會出現,有一個方法:

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

子類將有幾個新的方法,但大多隻是更改標註在我說的方式。

+1

只是使用extends關鍵字來擴展您的類。一點研究表明,擴展註釋是不可能的http://stackoverflow.com/questions/1624084/why-is-not-possible-to-extend-annotations-in-java http://www.cs.rice.edu /〜mgricken/research/xajavac/http://fusionsoft-online.com/en/java-annotations.html – 2013-02-12 20:21:52

+2

擴展類,覆蓋方法,使用新的註釋。雖然我質疑邏輯,但這是實現它的唯一方法。 – 2013-02-12 20:39:08

+2

@JeffHawthorne指的是別的東西。它說註釋本身不能被擴展,擴展類不能改變註釋。 – Joe 2013-02-12 20:45:33

回答

4

雖然我不知道你爲什麼會想,你需要擴展類,重載的方法,並應用註釋:

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

輸出:

某些值
其他值

+1

這樣的過程是否也可以應用於字段註釋(或者我應該問一個新問題)? – Matthieu 2015-10-13 05:59:37