简体   繁体   中英

java generic how to ensure type has specified annotation?

I'm trying to create a generic class in android using Java but I want to make sure that the type would take specific classes with specific annotations like this: I have class Table with annotation @Entity

@Entity
public class Table{}

and the generic class should only accept objects that have the @Entity annotation

if you want to check class annotation you have to use Reflection
http://static.javadoc.io/org.reflections/reflections/0.9.10/org/reflections/Reflections.html getTypesAnnotatedWith is the function you need

final Reflections reflections = new Reflections(packagePrefix);
    final Set<Class<?>> namedClasses = reflections.getTypesAnnotatedWith(Named.class);
    for (final Class<?> namedClass : namedClasses) {

    }

Simple answer: not possible.

Annotations represent meta information that isn't available when constructing classes using generic type parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM