get Property Get Methods - Java Reflection

Java examples for Reflection:Method

Description

get Property Get Methods

Demo Code

/**/* w ww .  j a va  2 s .  co m*/
 *all rights reserved,@copyright 2003
 */
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;

public class Main{
    public static void main(String[] argv) throws Exception{
        Class clz = String.class;
        System.out.println(java.util.Arrays.toString(getPropertyGetMethods(clz)));
    }
    public static final String PROPERTY_GET_METHOD_PREFIX = "get";
    public static final String PROPERTY_IS_METHOD_PREFIX = "is";
    /**
     *
     *
     * @param clz
     * @return
     */
    public static PropertyGetMethod[] getPropertyGetMethods(Class clz) {
        boolean startsWithGet = false;
        int index = 2;

        int count;
        ArrayList al = new ArrayList();

        Method[] ms = clz.getMethods();
        count = ms.length;
        for (int i = 0; i < count; i++) {
            Method m = ms[i];
            String name = m.getName();
            if ((startsWithGet = name
                    .startsWith(PROPERTY_GET_METHOD_PREFIX))
                    || name.startsWith(PROPERTY_IS_METHOD_PREFIX)) {
                //if the method's name starts with "get",
                //then the property name should be the substring from idnex 3;
                if (startsWithGet) {
                    index = 3;
                }

                //the getXXX  or isXXX method should have no Parameter;
                Class[] paramClasses = m.getParameterTypes();
                if (paramClasses.length == 0) {
                    Class c = m.getReturnType();
                    if (c == byte[].class || c == char[].class) {
                        al.add(0,
                                new PropertySetMethod(
                                        name.substring(index), c, m));
                    } else {
                        al.add(new PropertySetMethod(name.substring(index),
                                c, m));
                    }
                }
            }
        }

        return (PropertyGetMethod[]) al.toArray(new PropertyGetMethod[al
                .size()]);
    }
}

Related Tutorials