1

I have something like:

Field [] fields = claz.getDeclaredFields();
 for(Field f : fields){
    f.setAccessible(true);
    if(f.getType().equals(List.class)){
        Method m = f.getType().getMethod("size");
        int length = (Integer)m.invoke(f.get(node));
        System.out.println("length "+ length);
        }
}

it does work, but I'm wondering to know if there is any other good approaches, like something that will work for all other collections (TreeSet, HashSet, etc...), or the only way is that, I have to check for each type like what I already have?

thanks

3
  • Do you have to use reflection? Why not just use if (node instanceof Collection) length = ((Collection)node).size()?
    – Eran
    Jun 25, 2012 at 19:48
  • @eran You are on to something, but OP would need if (f.get(node) instanceof Collection), so reflection would still be used to access the field. Jun 25, 2012 at 19:50
  • @MarkoTopolnik, you're right, I overlooked that fact that node is the object whose fields are checked...
    – Eran
    Jun 25, 2012 at 19:55

3 Answers 3

2

In a Field object you could retrieve the Type and pass it as parameter for the method isAssignableFrom of Collection.class.

Like:

...
boolean isCollection = Collection.class.isAssignableFrom(f.getType())
...

From documentation the method isAssignableFrom:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

The same should be done with Map:

boolean isMap = Map.class.isAssignableFrom(f.getType());
0
2

Have you considered checking if the type implements the Map or Collection interfaces?

0

Collection.class.isAssignableFrom(f.getType()) will work for all collection types - all implementations of lists and sets.

Maps would have to be checked separately however, as they do not implement the Collection interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.