check for getter method and return the value. - Android java.lang.reflect

Android examples for java.lang.reflect:Java Bean

Description

check for getter method and return the value.

Demo Code


//package com.java2s;
import android.text.TextUtils;

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

    /**// w w  w  . j  a  v a2  s  . c  o  m
     * check for getter method and return the value.{@link #getGetter(Object, String)}.
     */
    public static Object getProperty(Object bean, String property) {
        if (bean == null || TextUtils.isEmpty(property)) {
            return null;
        }
        try {
            Method getter = getGetter(bean, property);
            if (getter != null) {
                if (!getter.isAccessible()) {
                    getter.setAccessible(true);
                }
                return getter.invoke(bean, new Object[0]);
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 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