Android examples for java.lang.reflect:Method Getter Setter
get Setter Method
//package com.java2s; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.WeakHashMap; import android.text.TextUtils; public class Main { private static final WeakHashMap<Field, Method> setterCache = new WeakHashMap<Field, Method>(); public static Method getSetter(Field field) { String fieldName = field.getName(); Method setter = (Method) setterCache.get(field); if (setter != null) { return setter; }/*from w w w . ja v a 2 s .c om*/ String methodName = generateSetterName(fieldName); Class<?> clazz = field.getDeclaringClass(); try { setter = clazz.getMethod(methodName, new Class[] { field.getType() }); setterCache.put(field, setter); return setter; } catch (SecurityException e) { return null; } catch (NoSuchMethodException e) { } return null; } public static String generateSetterName(String fieldName) { if (TextUtils.isEmpty(fieldName)) { throw new IllegalArgumentException("invalid field."); } String firstCH = fieldName.substring(0); Character secondCH = null; if (fieldName.length() > 1) { secondCH = Character.valueOf(fieldName.charAt(1)); } String setterName = null; if ((secondCH == null) || (!Character.isUpperCase(secondCH.charValue()))) { setterName = "set" + fieldName .replaceFirst(firstCH, firstCH.toUpperCase()); } else { setterName = "set" + fieldName; } return setterName; } }