Domanda

I am using Java7. I have a custom annotation created and annotated it on an Marker interface.

@SomeName(name="ABC")
public interface Bank{

}

Below is the class which implements the above interface.

public class BankImpl implements Bank{

//some code

}

Now i have a method in a separate class which takes above class as an input:

public void someMethod(Class class){

  //Here i need to get the custom annotation value
}

Above method is called as below:

someMethod(BankImpl.class);

Now inside someMethod() how can i get the annotation value?

Thanks!

È stato utile?

Soluzione 2

The problem is that the class itself does not have the annotation, therefore you'll get a null value when asking for the annotation. You really need to look into all the hierarchy of the class (i.e. superclass and interfaces):

import java.util.*;
import java.lang.annotation.*;

@Retention(value=RetentionPolicy.RUNTIME)
@interface SomeName {
    String name();
}

@SomeName(name = "ABC")
interface Bank {

}

class BankImpl implements Bank {
}

public class Test {
    public void someMethod(Class c) {
        Annotation annotation = c.getAnnotation(SomeName.class);

        if (annotation == null) {
            LinkedList<Class> queue = new LinkedList<Class>();
            queue.addLast(c.getSuperclass());

            for (Class cc : c.getInterfaces())
                queue.addLast(cc);

            while (!queue.isEmpty()) {
                c = queue.removeFirst();
                annotation = c.getAnnotation(SomeName.class);

                if (annotation != null)
                    break;              
            }
        }

        if (annotation == null)
            System.out.println("No such annotation !");
        else
            System.out.println("name is: " + ((SomeName)annotation).name());
    }

    public static void main(String... args) {
        Test test = new Test();
        test.someMethod(BankImpl.class);
    }
}

Altri suggerimenti

String someMethod(Class<Bank> clazz){
        SomeName sn = clazz.getAnnotation(SomeName.class);
        return sn.name();
    }

You only need the Class of the inteface to get everything of the Annotation which is annotated on the interface.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top