Here you can find the source of getGetterMethodForClass(Class cls, String beanName)
Parameter | Description |
---|---|
cls | the class to find the getter from |
beanName | the name of the java bean to find the getter for |
public static Method getGetterMethodForClass(Class cls, String beanName)
//package com.java2s; /********************************************************************** Copyright (c) 2004 Andy Jefferson and others. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at//from w w w. ja va2 s . com http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: ... **********************************************************************/ import java.lang.reflect.Method; public class Main { /** * Obtain a (Java bean) getter method from a class or superclasses using reflection. * Any 'get...' method will take precedence over 'is...' methods. * @param cls the class to find the getter from * @param beanName the name of the java bean to find the getter for * @return The getter Method */ public static Method getGetterMethodForClass(Class cls, String beanName) { Method getter = findDeclaredMethodInHeirarchy(cls, getJavaBeanGetterName(beanName, false)); if (getter == null) { getter = findDeclaredMethodInHeirarchy(cls, getJavaBeanGetterName(beanName, true)); } return getter; } private static Method findDeclaredMethodInHeirarchy(Class cls, String methodName, Class... parameterTypes) { try { do { try { return cls.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { cls = cls.getSuperclass(); } } while (cls != null); } catch (Exception e) { // do nothing } return null; } /** * Generate a JavaBeans compatible getter name * @param fieldName the field name * @param isBoolean whether the field is primitive boolean type * @return the getter name */ public static String getJavaBeanGetterName(String fieldName, boolean isBoolean) { if (fieldName == null) { return null; } return buildJavaBeanName(isBoolean ? "is" : "get", fieldName); } private static String buildJavaBeanName(String prefix, String fieldName) { int prefixLength = prefix.length(); StringBuilder sb = new StringBuilder(prefixLength + fieldName.length()); sb.append(prefix); sb.append(fieldName); sb.setCharAt(prefixLength, Character.toUpperCase(sb.charAt(prefixLength))); return sb.toString(); } }