/** * retourne une map contenant en clé le getter, et en valeur le setter. La map contient des * association de getter setter concernant le meme champs. ex: sur une classe Personne possédant * les méthodes suivantes: getPhone() setFirstName(...) getFirstName(); setLastName(...) * * @return */ public static HashMap<Method, Method> findGettersAndSetters(final Class<?> clazz) { final HashMap<Method, Method> map = new HashMap<Method, Method>(); final HashMap<String, Method> getters = new HashMap<String, Method>(); final HashMap<String, Method> setters = new HashMap<String, Method>(); for (final Method method : clazz.getMethods()) { if (ReflectionUtils.isGetter(method)) { getters.put(method.getName().replaceFirst("get", ""), method); } else if (ReflectionUtils.isSetter(method)) { setters.put(method.getName().replaceFirst("set", ""), method); } } for (final Entry<String, Method> entry : getters.entrySet()) { if (setters.containsKey(entry.getKey())) { final Method setter = setters.get(entry.getKey()); final Method getter = entry.getValue(); if (setter.getParameterTypes()[0].equals(getter.getReturnType())) { map.put(getter, setter); } } } return map; }
public static Method findSetter(final String fieldName, final Class<?> clazz) throws NoSuchMethodException { Preconditions.checkNotNull(fieldName, "fieldName cannot be null."); Preconditions.checkNotNull(clazz, "fieldName cannot be clazz."); final String getterName = "set" + StringUtils.capitalize(fieldName); for (final Method method : clazz.getMethods()) { if (ReflectionUtils.isSetter(method) && getterName.equals(method.getName())) { return method; } } throw new NoSuchMethodException( "no method " + getterName + " in class " + clazz.getSimpleName()); }