get the method start with 'get' or 'is'. - Android java.lang.reflect

Android examples for java.lang.reflect:Java Bean

Description

get the method start with 'get' or 'is'.

Demo Code


//package com.java2s;

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

import java.util.Map;

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<>();

    /**// ww  w  .  j av a 2  s.c  o m
     * get the method start with 'get' or 'is'.
     */
    public static Method getGetter(Object bean, String property) {
        Map<String, Method> cache = GETTER_CACHE.get(bean.getClass());
        if (cache == null) {
            cache = new ConcurrentHashMap<>();
            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 Tutorials