Reputation: 2084
I have a series of classes, which are unrelated. Each classs has one property with and @PrimaryKey (with getter and setter) that could be of any type. How can I use reflection to find which property of an instance of any class has the @PrimaryKey annotation - so I can get its value as a string.
The code doesn't know which type of class its being passed - it will just be of type "Object"
Upvotes: 0
Views: 1186
Reputation: 177
First of all you need to find all classes that may have the annotation in their members. This can be accomplished using 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);
}
}
}
Upvotes: -1
Reputation: 30568
You can do something like this:
for (Field field : YourClass.class.getDeclaredFields()) {
try {
Annotation annotation = field.getAnnotation(PrimaryKey.class);
// what you want to do with the field
} catch (NoSuchFieldException e) {
// ...
}
}
If you are working with the instance of your class then you can do this to get its class
object:
Class<?> clazz = instance.getClass();
so the first line becomes something like this:
instance.getClass().getDeclaredFields()
If you are in trouble you can always check out the official documentation. I believe it is quite good.
Upvotes: 2
Reputation: 15434
You can get all fields of a class and then iterate and find which field has your annotation:
Field[] fields = YourClass.class.getDeclaredFields();
for (Field field : fields) {
Annotation annot = field.getAnnotation(PrimaryKey.class);
if (annot != null) {
System.out.println("Found! " + field);
}
}
Upvotes: 2