Java Reflection Method Setter Get getSetter(String fieldName, Class clazz, Class fieldType)

Here you can find the source of getSetter(String fieldName, Class clazz, Class fieldType)

Description

Returns the setter-method for the given field name or null if no setter exists.

License

Apache License

Declaration

public static Method getSetter(String fieldName, Class<?> clazz, Class<?> fieldType) 

Method Source Code

//package com.java2s;
/**/*from  w  w w .  j av  a  2  s . co  m*/
 * Copyright 1996-2014 FoxBPM ORG.
 *
 * 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
 * 
 *      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.
 * 
 * @author kenshin
 */

import java.lang.reflect.Method;

public class Main {
    /**
     * Returns the setter-method for the given field name or null if no setter exists.
     */
    public static Method getSetter(String fieldName, Class<?> clazz, Class<?> fieldType) {
        String setterName = "set" + Character.toTitleCase(fieldName.charAt(0))
                + fieldName.substring(1, fieldName.length());
        try {
            // Using getMathods(), getMathod(...) expects exact parameter type
            // matching and ignores inheritance-tree.
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if (method.getName().equals(setterName)) {
                    Class<?>[] paramTypes = method.getParameterTypes();
                    if (paramTypes != null && paramTypes.length == 1 && paramTypes[0].isAssignableFrom(fieldType)) {
                        return method;
                    }
                }
            }
            return null;
        } catch (SecurityException e) {
            throw new RuntimeException(
                    "Not allowed to access method " + setterName + " on class " + clazz.getCanonicalName());
        }
    }
}

Related

  1. getSetter(final Object o, final String fieldName)
  2. getSetter(Method m)
  3. getSetter(Object instance, String methodName)
  4. getSetter(Object object, String name, Class type)
  5. getSetter(Object target, String property, Class parameterType)
  6. getSetter(String key, Class clazz, Class paramClazz)
  7. getSetter(String property, Object o)
  8. getSetter(String propertyName, Class clazz, Class arg)
  9. getSetter(String s)