[英]How can I make an object of class having private fields and constructor using reflection?
Let's say I have the following class假设我有以下课程
class Person
{
private double salary;
private Foo(double x, double y)
{
salary = x;
}
}
How would I create an instance of a class Person from outside and access its salary field using reflection?如何从外部创建类 Person 的实例并使用反射访问其工资字段?
Use Field.setAccessible(true) first if you're accessing it from a different class.如果您从不同的类访问它,请首先使用 Field.setAccessible(true)。
import java.lang.reflect.*;
class SomeObject{
private String string;
void setString(String value){
string= value;
}
}
class TestPrivateAccess{
public static void main(String[] args) throws Exception{
SomeObject ojb = new SomeObject();
obj.setString("astring");
Field field = SomeObject.class.getDeclaredField("string");
field.setAccessible(true);
Object value = field.get(obj);
System.out.println(value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.