find Getter from a class by name using reflection - Java Reflection

Java examples for Reflection:Java Bean

Description

find Getter from a class by name using reflection

Demo Code


//package com.java2s;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        String fieldName = "java2s.com";
        System.out.println(findGetter(clazz, fieldName));
    }//  w  w w.j  ava  2s . c  o m

    public static Method findGetter(Class<?> clazz, String fieldName) {
        for (Method method : findMethod(clazz, calcGetterName(fieldName))) {
            if (method.getParameterTypes().length == 0
                    && method.getReturnType() != null)
                return method;
        }

        for (Method method : findMethod(clazz,
                calcGetterNameBool(fieldName))) {
            if (method.getParameterTypes().length == 0
                    && method.getReturnType() == Boolean.class)
                return method;
        }

        return null;
    }

    public static List<Method> findMethod(Class<?> clazz, String name) {
        List<Method> ret = new ArrayList<Method>();
        for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
            Method[] methods = (c.isInterface() ? c.getMethods() : c
                    .getDeclaredMethods());
            for (Method method : methods) {
                if (name.equals(method.getName()))
                    ret.add(method);
            }
        }
        return ret;
    }

    public static String calcGetterName(String fieldName) {
        return "get" + ucfirst(fieldName);
    }

    public static String calcGetterNameBool(String fieldName) {
        return "is" + ucfirst(fieldName);
    }

    public static String ucfirst(String str) {
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }
}

Related Tutorials