Java Reflection Method Getter Get getGetter(Class clazz, String name)

Here you can find the source of getGetter(Class clazz, String name)

Description

get Getter

License

Apache License

Declaration

public static Method getGetter(Class clazz, String name) 

Method Source Code


//package com.java2s;
/*/*ww  w.j  a  v a  2s.c  o m*/
 *
 *  Copyright 2018 FJN Corp.
 *
 *  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                        Date                       Issue
 *  fs1194361820@163.com          2015-01-01                 Initial Version
 *
 */

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main {
    public static Method getGetter(Class clazz, String name) {
        return getSetterOrGetter(clazz, name, false);
    }

    private static Method getSetterOrGetter(Class clazz, String name, boolean isSetter) {
        String exceptMethodName = getSetterOrGetterName(name, isSetter);

        Method[] methods = clazz.getMethods();
        if (methods != null) {
            for (Method method : methods) {
                if (method.getName().equals(exceptMethodName) && !Modifier.isAbstract(method.getModifiers())
                        && Modifier.isPublic(method.getModifiers())) {
                    return method;
                }
            }
        }
        return null;
    }

    private static String getSetterOrGetterName(String name, boolean isSetter) {
        String prefix = isSetter ? "set" : "get";
        if (name == null || name.isEmpty() || name.trim().isEmpty()) {
            return prefix;
        }
        name = name.trim();
        return prefix + ("" + name.charAt(0)).toUpperCase() + (name.length() > 1 ? name.substring(1) : "");
    }
}

Related

  1. getGetter(A instance, String strAttributeName, Class clazz)
  2. getGetter(Class _class, String fieldName)
  3. getGetter(Class c, Field field)
  4. getGetter(Class clazz, Field field)
  5. getGetter(Class clazz, Field field)
  6. getGetter(Class cls, String name, Class type)
  7. getGetter(Class realClass, String pAttributeName)