Java examples for Reflection:Getter
Find the object getter method for the given property.
//package com.java2s; import java.lang.reflect.Method; public class Main { /**//from w ww . j a va 2s .c o m * Find the object getter method for the given property. * <p/> * If this method cannot find a 'get' property it tries to lookup an 'is' * property. * * @param object the object to find the getter method on * @param property the getter property name specifying the getter to lookup * @param path the full expression path (used for logging purposes) * @return the getter method */ public final static Method findGetter(Object object, String property, String path) { // Find the getter for property String getterName = toGetterName(property); Method method = null; Class sourceClass = object.getClass(); try { method = sourceClass.getMethod(getterName, (Class[]) null); } catch (Exception e) { } if (method == null) { String isGetterName = toIsGetterName(property); try { method = sourceClass .getMethod(isGetterName, (Class[]) null); } catch (Exception e) { StringBuilder buffer = new StringBuilder(); buffer.append("Result: neither getter methods '"); buffer.append(getterName).append("()' nor '"); buffer.append(isGetterName).append( "()' was found on class: '"); buffer.append(object.getClass().getName()).append("'."); throw new RuntimeException(buffer.toString(), e); } } return method; } /** * Return the getter method name for the given property name. * * @param property the property name * @return the getter method name for the given property name. */ public static String toGetterName(String property) { StringBuilder buffer = new StringBuilder(property.length() + 3); buffer.append("get"); buffer.append(Character.toUpperCase(property.charAt(0))); buffer.append(property.substring(1)); return buffer.toString(); } /** * Return the is getter method name for the given property name. * * @param property the property name * @return the is getter method name for the given property name. */ public static String toIsGetterName(String property) { StringBuilder buffer = new StringBuilder(property.length() + 3); buffer.append("is"); buffer.append(Character.toUpperCase(property.charAt(0))); buffer.append(property.substring(1)); return buffer.toString(); } }