java反射例子

来源:互联网 发布:单例模式 java csdn 编辑:程序博客网 时间:2024/06/05 23:05

bean:

public class InvokeBean {private int number;public int getNumber(){    return number;}private void setNumber(int num) {    this.number=num;}}

这里我们把set、方法设置为了private,利于反射可以访问该方法;

invoke实现:

public class Invock {public static InvokeBean getBean(int num) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {    //类加载器获取对象    ClassLoader loader=Thread.currentThread().getContextClassLoader();    Class class1=loader.loadClass("team.sss.InvokeBean");    //获取构造器实例化car    Constructor constructor=class1.getDeclaredConstructor((Class[]) null);    InvokeBean invokeBean=(InvokeBean) constructor.newInstance();    //方法反射设置属性    Method setNum=class1.getDeclaredMethod("setNumber", int.class);    System.out.println(setNum.getReturnType());    setNum.setAccessible(true);    setNum.invoke(invokeBean, num);    return invokeBean;}}

main:

    public static void main(String[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {        // TODO Auto-generated method stub        ClassLoader loader=Thread.currentThread().getContextClassLoader();        System.out.println("hello\n"+loader+"\n"+loader.getParent()+"\n"+loader.getParent().getParent());        System.out.println(new Invock().getBean(99).getNumber());    }

在访问private、protected成员变量或方法是必须通过

setAccessible(true); 方法取消java语言检查,否则将抛出IllegalAccessException

原创粉丝点击