◉◡◉ 您好,欢迎到访伊成个人站!

Class org.springframework.util.ReflectionUtils can not access a member of class异常

背景

最近,工作中多个地方用到了Java反射调用私有方法,但如果不小心很容易出错,下面看看异常信息

1
2
3
4
5
6
2020-09-25 14:02:03.393 ERROR 13920 --- [nio-8400-exec-3] c.s.b.d.support.utils.ExceptionUtils :
Could not access method:
Class org.springframework.util.ReflectionUtils can not access a member of class com.xxx.model.entity.XxxEntity with modifiers "private";
nested exception is java.lang.IllegalStateException: Could not access method:
Class org.springframework.util.ReflectionUtils can not access a member of
class com.xxx.Entity with modifiers "private"

举个栗子

为了完整的说明这个异常,简单的看一下代码:

Entity 类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.xxx.reflect;

public class Student {

private void add(){
System.out.println("add method...");
}

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类

1
2
3
4
5
6
7
8
public static void main(String[] args) throws Exception {

Class c1=Student.class;
Object obj=(Object)c1.newInstance();

Method method = c1.getDeclaredMethod("add");
method.invoke((Student)obj);
}

直接运行 main 方法则会报这个异常 Class . can not access a member of class . with modifiers “private” 。

解决方法

设置Field对象的Accessible的访问标志位为Ture,就可以通过反射获取私有变量的值,在访问时会忽略访问修饰符的检查。

所以只需要加上这行代码即可!

Main类

1
2
3
4
5
6
7
8
9
public static void main(String[] args) throws Exception {

Class c1=Student.class;
Object obj=(Object)c1.newInstance();

Method method = c1.getDeclaredMethod("add");
method.setAccessible(true); // 加上这句即可解决问题!
method.invoke((Student)obj);
}

The end

支付宝打赏 微信打赏