Java Reflection Method Getter Get getGetter(Object bean, String property)

Here you can find the source of getGetter(Object bean, String property)

Description

get Getter

License

Apache License

Declaration

public static Method getGetter(Object bean, String property) 

Method Source Code

//package com.java2s;
/*/* ww  w  .  jav a  2  s .co  m*/
 * Copyright 2011-2013 HTTL Team.
 *  
 * 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.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class Main {
    private static final ConcurrentMap<Class<?>, Map<String, Method>> GETTER_CACHE = new ConcurrentHashMap<Class<?>, Map<String, Method>>();

    public static Method getGetter(Object bean, String property) {
        Map<String, Method> cache = GETTER_CACHE.get(bean.getClass());
        if (cache == null) {
            cache = new ConcurrentHashMap<String, Method>();
            for (Method method : bean.getClass().getMethods()) {
                if (Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers())
                        && !void.class.equals(method.getReturnType()) && method.getParameterTypes().length == 0) {
                    String name = method.getName();
                    if (name.length() > 3 && name.startsWith("get")) {
                        cache.put(name.substring(3, 4).toLowerCase() + name.substring(4), method);
                    } else if (name.length() > 2 && name.startsWith("is")) {
                        cache.put(name.substring(2, 3).toLowerCase() + name.substring(3), method);
                    }
                }
            }
            Map<String, Method> old = GETTER_CACHE.putIfAbsent(bean.getClass(), cache);
            if (old != null) {
                cache = old;
            }
        }
        return cache.get(property);
    }
}

Related

  1. getGetter(Class realClass, String pAttributeName)
  2. getGetter(final Class clazz, final String propertyName)
  3. getGetter(final Class clazz, final String fieldName)
  4. getGetter(final Class clz, final String propertyName)
  5. getGetter(final Object o, final String fieldName)
  6. getGetter(Object instance, String methodName)
  7. getGetter(Object o, String name)
  8. getGetter(Object object, String name)
  9. getGetter(String key, Class clazz)