Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that java.lang.reflect.Method return type is Collection?

I have method to get list of bean properities like below. How to check that method return type is collection (like List, Set...). isInstance(Collection.class) doesn't work.

public static List<String> getBeanProperties(String className, boolean withLists) {

    ArrayList<String> a = new ArrayList();
    try {
        Class c = Class.forName(className);
        Method methods[] = c.getMethods();
        for (int i = 0; i < methods.length; i++) {
            String m = methods[i].getName();
            if(m.startsWith("get") && methods[i].getParameterTypes().length == 0) {

                if((methods[i].getReturnType().isInstance(Collection.class)) && !withLists) {
                    // skip lists
                } else {
                    String f = m.substring(3);
                    char ch = f.charAt(0);
                    char lower = Character.toLowerCase(ch);
                    f = lower + f.substring(1);
                    a.add(f);
                }
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return a;
}
like image 971
marioosh Avatar asked Nov 03 '10 12:11

marioosh


2 Answers

use Collection.class.isAssignableFrom(returnType). Reference

like image 113
Bozho Avatar answered Sep 28 '22 00:09

Bozho


Method#getReturnType returns a single Class object, the Class object that corresponds to the method declaration. If the method is declared to return a Collection, you'll see a collection. If it is declared to return a subclass of Collection (List', ..), you'll need to check, ifCollection` is assignable from the actual return type:

 Class<?> realClass = methods[i].getReturnType(); // this is a real class / implementation
 if (Collection.isAssignableFrom(realClass)) {
    // skip collections (sic!)
 }
like image 26
Andreas Dolk Avatar answered Sep 28 '22 01:09

Andreas Dolk