集册 Java实例教程 获取读取方法

获取读取方法

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

453
获取读取方法


//package com.nowjava;

import java.lang.reflect.Method;
//来 自 时 代 J a v a 公 众 号

public class Main {


    @SuppressWarnings({ "rawtypes", "unchecked" })

    public static Method getReadMethod(Class clazz, String propertyName) {

        Method readMethod = null;

        String base = capitalize(propertyName);


        // Since there can be multiple setter methods but only one getter

        // method, find the getter method first so that you know what the

        // property type is. For booleans, there can be "is" and "get"

        // methods. If an "is" method exists, this is the official
        /**
         from
        * nowjava.com - 时  代  Java 
        **/

        // reader method so look for this one first.

        try {

            readMethod = clazz.getMethod("is" + base, (Class[]) null);

        } catch (Exception getterExc) {

            try {

                // no "is" method, so look for a "get" method.

                //if (clazz == null) return null;

                readMethod = clazz.getMethod("get" + base, (Class[]) null);

            } catch (Exception e) {

                // no is and no get, we will return null

            }

        }


        return readMethod;

    }


    private static String capitalize(String s) {

        
展开阅读全文