java反射调用方法时,Class . can not access a member of class . with modifiers "private" 等异常解决

来源:互联网 发布:淘宝企业店铺委托书 编辑:程序博客网 时间:2024/05/25 08:13

先看javabean类:目的使用反射调用私有方法:

package com.imooc.reflect;public class Student {    private void add(){        System.out.println("增加数据!");    }    private int id;    private String name;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Student(int id, String name) {        super();        this.id = id;        this.name = name;    }    public Student() {    }}

main测试方法

public static void main(String[] args) throws Exception {        Class c1=Student.class;        Object obj=(Object)c1.newInstance();        Method  add = c1.getDeclaredMethod("add");        add.invoke((Student)obj);    }

这时,就会报Class . can not access a member of class . with modifiers “private” 异常。
解决方案:添加一行代码:add.setAccessible(true);

Method  add = c1.getDeclaredMethod("add");add.setAccessible(true);add.invoke((Student)obj);

当然最后调用时也可以写成:add.invoke(obj);

0 0