集册 Java实例教程 使用反射通过名称从类中找到Setter

使用反射通过名称从类中找到Setter

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

423
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用反射通过名称从类中找到Setter
//时 代      J a v a   公   众 号 - nowjava.com

//package com.nowjava;


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 = "nowjava.com";

        System.out.println(findSetter(clazz, fieldName));

    }


    public static Method findSetter(Class<?> clazz, String fieldName) {

        List<Method> methods = findMethod(clazz, calcSetterName(fieldName));

        methods.addAll(findMethod(clazz, fieldName));


        for (Method method : methods) {

            if (method != null && method.getParameterTypes().length == 1)/* from N o  w  J a v a . c o m - 时  代  Java*/

                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 
展开阅读全文