Java Reflection Method Setter Get getSetterShorthandName(Method method)

Here you can find the source of getSetterShorthandName(Method method)

Description

get Setter Shorthand Name

License

Apache License

Declaration

public static String getSetterShorthandName(Method method) 

Method Source Code

//package com.java2s;
/* 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 .j  a  va 2s  . 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.
 */

import java.lang.reflect.Method;

import java.util.Locale;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern SETTER_PATTERN = Pattern
            .compile("set[A-Z].*");

    public static String getSetterShorthandName(Method method) {
        if (!isSetter(method)) {
            return method.getName();
        }

        String name = method.getName();
        if (name.startsWith("set")) {
            name = name.substring(3);
            name = name.substring(0, 1).toLowerCase(Locale.ENGLISH)
                    + name.substring(1);
        }

        return name;
    }

    public static boolean isSetter(Method method,
            boolean allowBuilderPattern) {
        String name = method.getName();
        Class<?> type = method.getReturnType();
        Class<?> params[] = method.getParameterTypes();

        if (!SETTER_PATTERN.matcher(name).matches()) {
            return false;
        }

        return params.length == 1
                && (type.equals(Void.TYPE) || (allowBuilderPattern && method
                        .getDeclaringClass().isAssignableFrom(type)));
    }

    public static boolean isSetter(Method method) {
        return isSetter(method, false);
    }

    private static boolean matches(Class<?>[] parameterTypes, Object[] args) {
        if ((parameterTypes == null) || (parameterTypes.length == 0)) {
            return ((args == null) || (args.length == 0));
        }
        if ((args == null) || (parameterTypes.length != args.length)) {
            return false;
        }
        for (int i = 0; i < parameterTypes.length; i++) {
            if ((args[i] != null)
                    && (!parameterTypes[i].isAssignableFrom(args[i]
                            .getClass()))) {
                return false;
            }
        }
        return true;
    }
}

Related

  1. getSetters(Class clazz)
  2. getSetters(Class clazz)
  3. getSetters(Class klass)
  4. getSetters(Object obj)
  5. getSettersForType(Class clazz, String typeName)
  6. getSetterType(Method method)