Android examples for java.lang.reflect:Method Getter Setter
get Getter Method
//package com.java2s; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.WeakHashMap; public class Main { private static final WeakHashMap<Field, Method> getterCache = new WeakHashMap<Field, Method>(); public static Method getGetter(Field field) { String fieldName = field.getName(); Method getter = (Method) getterCache.get(field); if (getter != null) { return getter; }/*from www .j a v a2s . c o m*/ String methodName = generateGetterName(fieldName, field.getType() == Boolean.TYPE); Class<?> clazz = field.getDeclaringClass(); try { getter = clazz.getMethod(methodName, (Class<?>[]) null); getterCache.put(field, getter); return getter; } catch (SecurityException e) { return null; } catch (NoSuchMethodException e) { } return null; } public static String generateGetterName(String fieldName) { return generateGetterName(fieldName, false); } public static String generateGetterName(String fieldName, boolean isPrimitiveBoolean) { String firstCH = "" + fieldName.charAt(0); Character secondCH = null; if (fieldName.length() > 1) { secondCH = Character.valueOf(fieldName.charAt(1)); } String getterName = null; String replaceStr = null; if ((secondCH == null) || (!Character.isUpperCase(secondCH.charValue()))) { replaceStr = fieldName.replaceFirst(firstCH, firstCH.toUpperCase()); } else { replaceStr = fieldName; } if (isPrimitiveBoolean) { getterName = "is" + replaceStr; } else { getterName = "get" + replaceStr; } return getterName; } }