反射生成对象 获得方法及构造器

来源:互联网 发布:手机淘宝咋退货退款 编辑:程序博客网 时间:2024/06/06 03:59

实体类:

package com.ashin.test;public class AshinDemo {    private String name;    private String id;    public AshinDemo(String name, String id) {        super();        this.name = name;        this.id = id;    }    public String getName() {        return name;    }    private void setName(String name) {        this.name = name;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    @Override    public String toString() {        return "AshinDemo [name=" + name + ", id=" + id + "]";    }}

反射类

package com.ashin.test;import java.lang.reflect.Constructor;import java.lang.reflect.Method;public class ReflectDemo {    /**     * @param args     * @throws Exception      */    public static void main(String[] args) throws Exception {        //生成当前线程的类加载器        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();        //加载类        @SuppressWarnings("unchecked")        Class<AshinDemo> clazz = (Class<AshinDemo>) classLoader.loadClass("com.ashin.test.AshinDemo");        //获得构造器        Constructor<AshinDemo> constructor =clazz.getConstructor(String.class,String.class);        //使用获得的构造器生成对象        AshinDemo ashinDemo =  (AshinDemo)constructor.newInstance("ashin","01");        //使用获得的构造器获得方法        Method setName =clazz.getMethod("setName", String.class);        //使用invouke来使用获得的方法        setName.invoke(ashinDemo, "Ben");        //使用获得的构造器获得方法   实体类中是私有的  暴力访问getDeclaredMethod        Method setName2 =clazz.getDeclaredMethod("setName", String.class);        //取消java语言的访问检查        setName2.setAccessible(true);        //使用invouke来使用获得的方法        setName.invoke(ashinDemo, "Ben");        System.out.println(ashinDemo);    }}
0 0
原创粉丝点击