标题可能有点难以理解,但让我简单地描述一下我的问题。
假设我有一个这样的注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Identifier {
}
现在,我创建一个类,用它来注释其任何字段:
public class Student {
private String name;
private String surname;
@Identifier
private String idNumber;
...
}
最后,在运行时,我想创建一个Map
键类型为typeof(field annotated with @Identifier)
和值类型为的Student
。请注意,任何字段都可以用注释@Identifier
。
有任何想法吗?
编辑
好吧,让我澄清一下:
class Student {
private String name;
private String surname;
@Identifier
private String idNumber;
}
class Foo {
@Identifier
private Integer x;
}
// Now, what I want to have are two maps:
SortedMap students; // key type: String
// value type: Student
SortedMap foos; // key type: Integer
// value type: Foo
提前致谢!
我仍然不确定您要做什么。
在运行时,我想创建一个键类型为typeof(以@Identifier注释的字段)和Student类型为值的Map
您可以创建原始Map
或Map<Object, Object>
。您可以使用注释字段的类型@Identifier
。我不确定“学生”的值类型是什么意思,所以我假设您的意思是类型Student
,即。它的Class
对象。
public static void main(String[] args) throws Exception {
Class<?> clazz = Student.class;
Map<Object, Object> map = new HashMap<>();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
Identifier annotation = field.getAnnotation(Identifier.class);
if (annotation != null) {
map.put(field.getType(), clazz);
}
}
System.out.println(map);
}
在您的示例课有问题的情况下,将显示以下内容
{class java.lang.String=class com.spring.Student}
因此,带注释的字段类型将映射到类类型。
您将无法使用,Map<String,Student>
因为您在编译时不知道类型String
(甚至可能不知道Student
)。您可以尝试强制转换,但要为自己设置多个ClassCastException
s。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句