2

I have one Java class that uses annotations. I want to write a version that extends it and changes the annotations on existing methods.

So there will be a method that has:

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

The subclass will have a couple new methods, but will mostly just change annotations in the manner I said.

Joe
  • 7,922
  • 18
  • 54
  • 83
  • 1
    to extend your class just use the extends keyword. a little research suggests that extending annotations is not possible 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 – Jeff Hawthorne Feb 12 '13 at 20:21
  • 2
    extend class, override methods, use new annotations. Though I question the logic, that's pretty much the only way to do it. – Brian Roach Feb 12 '13 at 20:39
  • 2
    @JeffHawthorne that refers to something else. It says that annotations themselves can't be extended, not extended classes can't change annotations. – Joe Feb 12 '13 at 20:45

1 Answers1

4

Though I'm not sure why you'd want to, you'd need to extend the class, override the methods, and apply the annotations:

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

Output:

Some value
Some other value

Brian Roach
  • 76,169
  • 12
  • 136
  • 161