java泛型如何确保类型有指定的注解?
java generic how to ensure type has specified annotation?
我正在尝试使用 Java 在 android 中创建一个通用的 class,但我想确保该类型将采用特定的 classes像这样的注释:
我有 class Table
注释 @Entity
@Entity
public class Table{}
和通用 class 应该只接受具有 @Entity
注释的对象
如果你想检查 class 注释你必须使用反射
http://static.javadoc.io/org.reflections/reflections/0.9.10/org/reflections/Reflections.html
getTypesAnnotatedWith
就是你需要的功能
final Reflections reflections = new Reflections(packagePrefix);
final Set<Class<?>> namedClasses = reflections.getTypesAnnotatedWith(Named.class);
for (final Class<?> namedClass : namedClasses) {
}
简单回答:不可能。
注释表示使用通用类型参数构造 类 时不可用的元信息。
我正在尝试使用 Java 在 android 中创建一个通用的 class,但我想确保该类型将采用特定的 classes像这样的注释:
我有 class Table
注释 @Entity
@Entity
public class Table{}
和通用 class 应该只接受具有 @Entity
注释的对象
如果你想检查 class 注释你必须使用反射
http://static.javadoc.io/org.reflections/reflections/0.9.10/org/reflections/Reflections.html
getTypesAnnotatedWith
就是你需要的功能
final Reflections reflections = new Reflections(packagePrefix);
final Set<Class<?>> namedClasses = reflections.getTypesAnnotatedWith(Named.class);
for (final Class<?> namedClass : namedClasses) {
}
简单回答:不可能。
注释表示使用通用类型参数构造 类 时不可用的元信息。