集册 Java实例教程 获取属性获取方法

获取属性获取方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

400
获取属性获取方法

/**

 *all rights reserved,@copyright 2003

 */
 /**来自 
  时 代      J a v a   公   众 号 - nowjava.com**/

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) {// from N o w  J a v a  . c o m

        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,

                                
展开阅读全文