Java Reflection Method Getter Get getGetters(Class clazz)

Here you can find the source of getGetters(Class clazz)

Description

get a map of public getters (propertyName -> Method)

License

Apache License

Parameter

Parameter Description
clazz a parameter

Declaration

public static Map<String, Method> getGetters(Class<?> clazz) 

Method Source Code


//package com.java2s;
/*//  ww  w .ja v  a 2  s . c om
 * Copyright 2008-2009 the original author or authors.
 *
 * 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;
import java.util.HashMap;
import java.util.Map;

public class Main {
    /**
     * get a map of public getters (propertyName -> Method)
     * 
     * @param clazz
     * @return
     */
    public static Map<String, Method> getGetters(Class<?> clazz) {
        Map<String, Method> getters = new HashMap<String, Method>();
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            if (method.getParameterTypes().length == 0) {
                if (methodName.startsWith("get") && methodName.length() > 3) {
                    String propertyName = methodName.substring(3, 4).toLowerCase();
                    if (methodName.length() > 4) {
                        propertyName += methodName.substring(4);
                    }
                    getters.put(propertyName, method);
                } else if (methodName.startsWith("is") && methodName.length() > 2
                        && Boolean.TYPE.equals(method.getReturnType())) {
                    String propertyName = methodName.substring(2, 3).toLowerCase();
                    if (methodName.length() > 3) {
                        propertyName += methodName.substring(3);
                    }
                    getters.put(propertyName, method);
                }
            }
        }
        return getters;
    }
}

Related

  1. getGetters(Class c)
  2. getGetters(Class clazz)
  3. getGetters(Class klass)
  4. getGetters(Class c)
  5. getGetters(Class clazz)
  6. getGetters(final Class clazz)
  7. getGetters(Object bean)
  8. getGetters(Object obj)
  9. getGettersAndSetters(Object obj)