get Property Set Methods - Java Reflection

Java examples for Reflection:Method

Description

get Property Set Methods

Demo Code

/**/*w  ww. java  2 s .c om*/
 *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(getPropertySetMethods(clz)));
    }
    public static final String PROPERTY_SET_METHOD_PREFIX = "set";
    /**
     *
     * @param clz
     * @return
     */
    public static PropertySetMethod[] getPropertySetMethods(Class clz) {
        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 (name.startsWith(PROPERTY_SET_METHOD_PREFIX)) {
                //the setXXX  method should have only one Parameter;
                Class[] paramClasses = m.getParameterTypes();
                if (paramClasses.length == 1) {
                    Class c = paramClasses[0];
                    //note: the name of the property should be the substring from the index 3;
                    if (c == byte[].class || c == char[].class) {
                        al.add(0, new PropertySetMethod(name.substring(3),
                                paramClasses[0], m));
                    } else {
                        al.add(new PropertySetMethod(name.substring(3),
                                paramClasses[0], m));
                    }
                }
            }
        }

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

Related Tutorials