Java Reflection Method Setter Get getSetterMethod(Class type, String property)

Here you can find the source of getSetterMethod(Class type, String property)

Description

get Setter Method

License

Apache License

Declaration

public static Method getSetterMethod(Class type, String property) throws NoSuchMethodException 

Method Source Code

//package com.java2s;
/*//from w ww  . j a  va 2 s  .  c o m
 * Copyright 2007-2013 Ben Galbraith.
 *
 * 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.
 */

import java.lang.reflect.Method;

public class Main {
    public static Method getSetterMethod(Class type, String property) throws NoSuchMethodException {
        String setterName = getEtterMethodName(property, "set");

        Method setterMethod = null;
        Method[] methods = type.getMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            if (method.getName().equals(setterName)) {
                if (setterMethod != null)
                    throw new IllegalStateException(String.format(
                            "Type '%1$s' has more than one method named '%2$s'; use getSetterMethod(Class, String, Class) to obtain the right one",
                            type, setterName));
                setterMethod = method;
            }
        }

        if (setterMethod == null)
            throw new NoSuchMethodException(String.format("No setter method for property '%1$s'", property));

        return setterMethod;
    }

    public static Method getSetterMethod(Class type, String property, Class... parameters)
            throws NoSuchMethodException {
        String setterName = getEtterMethodName(property, "set");
        return type.getMethod(setterName, parameters);
    }

    public static String getEtterMethodName(String property, String type) {
        return type + property.substring(0, 1).toUpperCase() + property.substring(1);
    }
}

Related

  1. getSetterFromCache(Class clazz)
  2. getSetterMap(Class cls)
  3. getSetterMethod(Class beanClass, String fieldName, List supportedTypes)
  4. getSetterMethod(Class c, String methodName)
  5. getSetterMethod(Class containingClass, Class propertyType, String propertyName)
  6. getSetterMethod(Class beanClass, String property)
  7. getSetterMethod(Class classType, String fieldName, Class paramType)
  8. getSetterMethod(Class clazz, Field field)
  9. getSetterMethod(Class clazz, String name)