如何查找哪个java bean属性具有已知注释

时间:2012-12-20 12:47:41

标签: java reflection annotations

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

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

3 个答案:

答案 0 :(得分: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()

如果您遇到麻烦,可以随时查看官方documentation。我相信这很好。

答案 1 :(得分:2)

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

Field[] fields = YourClass.class.getDeclaredFields();
for (Field field : fields) {
    Annotation annot = field.getAnnotation(PrimaryKey.class);  
    if (annot != null) {
        System.out.println("Found! " + field);
    }
}

答案 2 :(得分:-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);
        }
    }
}