Java examples for Reflection:Setter
Find the source object setter method for the given property.
//package com.java2s; import java.lang.reflect.Method; public class Main { /**//from w w w . j a va2 s . c o m * Find the source object setter method for the given property. * * @param source the source object to find the setter method on * @param property the property which setter needs to be looked up * @param targetClass the setter parameter type * @param path the full expression path (used for logging purposes) * @return the setter method */ public final static Method findSetter(Object source, String property, Class targetClass, String path) { Method method = null; // Find the setter for property String setterName = toSetterName(property); Class sourceClass = source.getClass(); Class[] classArgs = { targetClass }; try { method = sourceClass.getMethod(setterName, classArgs); } catch (Exception e) { // Log detailed error message of why setter lookup failed StringBuilder buffer = new StringBuilder(); buffer.append("Result: setter method '"); buffer.append(setterName).append("(") .append(targetClass.getName()); buffer.append(")' was not found on class '"); buffer.append(source.getClass().getName()).append("'."); throw new RuntimeException(buffer.toString(), e); } return method; } /** * Return the setter method name for the given property name. * * @param property the property name * @return the setter method name for the given property name. */ public static String toSetterName(String property) { StringBuilder buffer = new StringBuilder(property.length() + 3); buffer.append("set"); buffer.append(Character.toUpperCase(property.charAt(0))); buffer.append(property.substring(1)); return buffer.toString(); } }