Gets the getters of a pojo as a map of String as key and Method as value.
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
public class Util{
static final String GET = "get";
static final String IS = "is";
static final String SET = "set";
/**
* Gets the getters of a pojo as a map of {@link String} as key and
* {@link Method} as value.
*/
public static Map<String,Method> getGetterMethods(Class<?> pojoClass)
{
HashMap<String,Method> methods = new HashMap<String,Method>();
fillGetterMethods(pojoClass, methods);
return methods;
}
private static void fillGetterMethods(Class<?> pojoClass, Map<String,Method> baseMap)
{
if(pojoClass.getSuperclass()!=Object.class)
fillGetterMethods(pojoClass.getSuperclass(), baseMap);
Method[] methods = pojoClass.getDeclaredMethods();
for (int i=0;i<methods.length;i++)
{
Method m=methods[i];
if (!Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length==0 &&
m.getReturnType()!=null && Modifier.isPublic(m.getModifiers()))
{
String name=m.getName();
if (name.startsWith(IS))
baseMap.put(toProperty(IS.length(), name), m);
else if (name.startsWith(GET))
baseMap.put(toProperty(GET.length(), name), m);
}
}
}
/**
* Converts a method name into a camel-case field name, starting from {@code start}.
*/
public static String toProperty(int start, String methodName)
{
char[] prop = new char[methodName.length()-start];
methodName.getChars(start, methodName.length(), prop, 0);
int firstLetter = prop[0];
prop[0] = (char)(firstLetter<91 ? firstLetter + 32 : firstLetter);
return new String(prop);
}
}
Related examples in the same category