JDK动态代理(2)--------反射Method的作用

Person类做例子

package com.spring.aop.proxy;

public class Preson {
    Preson() {
        System.out.println("this is person Constructor");
    }
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


}

MethodReflect做实际操作

package com.spring.aop.proxy;

import java.lang.reflect.Method;

public class MethodReflect {
     /**
     * 调用反射类中的方法
     */
    public static void main(String[] args) {
        try {
            //属性名称
            String attrbute = "name"; 
            Class<?> cls = Class.forName(Preson.class.getName());
            Object obj = cls.newInstance();
            //initcap(attrbute)返回"Name"
            //获取Preson类中setName实际方法
            Method setMethod = cls.getMethod("set" + initcap(attrbute), String.class);
            //获取Preson类中getName方法
            Method getMethod = cls.getMethod("get" + initcap(attrbute)); 
            
            //invoke相当于 实例化的类调用.setName("")
            setMethod.invoke(obj, "liuqiangaa");
          //相当于 例化的类调用.getName()
            System.out.println(getMethod.invoke(obj)); 
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //将字符串的首字母变为大写字母
    public static String initcap(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }


}

猜你喜欢

转载自www.cnblogs.com/zhougongjin/p/10601627.html