0

我有一系列不相关的课程。每个类都有一个属性和 @PrimaryKey(带有 getter 和 setter),可以是任何类型。如何使用反射来查找任何类的实例的哪个属性具有 @PrimaryKey 注释 - 这样我就可以将其值作为字符串获取。

代码不知道它传递的是哪种类型的类 - 它只是“对象”类型

4

3 回答 3

2

你可以这样做:

for (Field field : YourClass.class.getDeclaredFields()) {
    try {
        Annotation annotation = field.getAnnotation(PrimaryKey.class);
        // what you want to do with the field
    } catch (NoSuchFieldException e) {
        // ...
    }
}

如果你正在使用你的类的实例,那么你可以这样做来获取它的class对象:

Class<?> clazz = instance.getClass();

所以第一行变成了这样:

instance.getClass().getDeclaredFields()

如果您遇到麻烦,您可以随时查看官方文档。我相信它非常好。

于 2012-12-20T12:51:37.620 回答
2

您可以获取一个类的所有字段,然后迭代并找到哪个字段有您的注释:

Field[] fields = YourClass.class.getDeclaredFields();
for (Field field : fields) {
    Annotation annot = field.getAnnotation(PrimaryKey.class);  
    if (annot != null) {
        System.out.println("Found! " + field);
    }
}
于 2012-12-20T12:52:03.163 回答
-1

首先,您需要找到所有可能在其成员中具有注释的类。这可以使用 Spring Framework 来完成ClassUtils

    public static void traverse(String classSearchPattern, TypeFilter typeFilter) {
    ClassLoader classLoader = ClassUtils.getDefaultClassLoader();
    ResourcePatternResolver resourceResolver = new    PathMatchingResourcePatternResolver(classLoader);

    Resource[] resources = null;
    try {
        resources = resourceResolver.getResources(classSearchPattern);
    } catch (IOException e) {
        throw new FindException(
                "An I/O problem occurs when trying to resolve resources matching the pattern: "
                        + classSearchPattern, e);
    }

    MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();

    for (Resource resource : resources) {
        try {
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);

            if (typeFilter.match(metadataReader, metadataReaderFactory)) {
                String className = metadataReader.getClassMetadata().getClassName();
                Class<?> annotatedClass = classLoader.loadClass(className);

        // CHECK IF THE CLASS HAS PROPERLY ANNOTATED FIELDS AND 
        // DO SOMETHING WITH THE CLASS FOUND... E.G., PUT IT IN SOME REGISTRY 

            }
        } catch (Exception e) {
            throw new FindException("Failed to analyze annotation for resource: " + resource, e);
        }
    }
}
于 2012-12-20T13:00:13.090 回答