jeudi 19 mai 2016

Convert Java Object/String to actual Class

I get a list of Java classes via:

List<String> cF = classFinder.findClassesInPackage("com.some.test", Info.class); 

where classFinder is the service/class and findClassesInPackage method finds all the classes in a package com.some.test that has @Info annotations in them. Info.class is the second parameter which is nothing but the interface.

My list cF is now filled with following content:

[com.some.test.example.FollTest, com.some.test.example.SubsTest, ..]

Now, I convert this List cF to a Set to remove duplicate methods via:

Set<String> set = new HashSet<String>(cF);

OBJECTIVE:

I want to iterate over this set so I can get all the classes one-by-one and finally get all the Info annotations in each class and print them. I need this as I will parse these annotation afterwards.

My concern: The set elements are now Strings and how do I convert them to actual Classes? (For example: out of my first element in set: com.some.test.example.FollTest, I just want FollTest that too in class form)

Here is what I am trying to do for a single element first:

Object check = set.toArray()[0]; - still an Object/String and not the actual class which I want.

And then for reading the annotations (for example):

for (Annotation annotation : ClassName.class.getAnnotations()) {
            Class<? extends Annotation> type = annotation.annotationType();
            System.out.println("Values of " + type.getName());

            for (Method method : type.getDeclaredMethods()) {
                Object value = method.invoke(annotation, (Object[])null);
                System.out.println(" " + method.getName() + ": " + value);
            }
        }

How do I get above ClassName? (although I have them in the String/Object form as part of list/set). I feel there can be a better approach to this. Something like Class.cast(Object) / Class.cast(String).

Referred this:http://ift.tt/1XDGJ5R for how I can get the annotations in a particular class.

Aucun commentaire:

Enregistrer un commentaire