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

I have a method for getting a list of bean properties as shown below. How to check that the type of the returned method is a collection (e.g. List, Set ...). isInstance (Collection.class) does not 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; } 
+4
source share
2 answers

use Collection.class.isAssignableFrom(returnType) . Link

+13
source

Method#getReturnType returns a single class object, a class object corresponding to a method declaration. If the return a Collection method is declared, you will see the collection. If it is declared to return a subclass of Collection ( List', ..), you'll need to check, if Collection` can be assigned from the actual return type:

  Class<?> realClass = methods[i].getReturnType(); // this is a real class / implementation if (Collection.isAssignableFrom(realClass)) { // skip collections (sic!) } 
+1
source

All Articles