How to check if an annotation belongs to a class in a certain category?

I have classes that are annotated as follows:

@BaseProp(category = Property.CATEGORY1)
where Property is a class defined as  
 public enum Property{
CATEGORY1("category1"), CATTEGORY2("category2");

    public static Property getCategory(String value) {
        return Property
                .valueOf(Optional.ofNullable(value).orElseThrow(IllegalArgumentException::new).toUpperCase());
    }

It has corresponding getters, setters, constructors, and this method getCategory().

My other classes in multiple packages are annotated as

@Prop(category = Property.CATGORY1)

These classes extend the base class.

I want to create two ArrayListobjects for classes - 1., which extends BaseClass, and the category is annotated as CATEGORY1 2., which extends BaseClass, and the category is annotated as CATEGORY2

In the sense that I want to define classes and create objects for them and put them in a common ArrayListof Objectx.

How to do this using reflections and Java?

+4
1

(, X BaseClass) - :

Class<?> c = X.class;  // or if you have X x, then x.getClass();
for (Annotation ann : c.getAnnotations()) {
  if (ann instanceof BaseProp) {   // make sure it your annotation
    BaseProp bp = (BaseProp)ann;
    bp.category();  // do something here
  }
}

"// - ", , .

+2

All Articles