Here you can find the source of getSetterMethodForClass(Class cls, String beanName, Class type)
Parameter | Description |
---|---|
cls | the class to find the setter from |
beanName | the name of the java bean to find the setter for |
type | the type of the java bean to find the setter for |
public static Method getSetterMethodForClass(Class cls, String beanName, Class type)
//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 ww w . j a va 2 s. co m*/ 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) setter method from a class or superclasses using reflection. * @param cls the class to find the setter from * @param beanName the name of the java bean to find the setter for * @param type the type of the java bean to find the setter for * @return The setter Method */ public static Method getSetterMethodForClass(Class cls, String beanName, Class type) { return findDeclaredMethodInHeirarchy(cls, getJavaBeanSetterName(beanName), type); } 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 setter name * @param fieldName the field name * @return the setter name */ public static String getJavaBeanSetterName(String fieldName) { if (fieldName == null) { return null; } return buildJavaBeanName("set", 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(); } }