java 反射私有变量,通过反射访问Java中的私有变量

I'm trying to write a method that will get a private field in a class using reflection.

Here's my class (simplified for this example):

public class SomeClass {

private int myField;

public SomeClass() {

myField = 42;

}

public static Object getInstanceField(Object instance, String fieldName) throws Throwable {

Field field = instance.getClass().getDeclaredField(fieldName);

return field.get(instance);

}

}

So say I do this:

SomeClass c = new SomeClass();

Object val = SomeClass.getInstanceField(c, "myField");

I'm getting an IllegalAccessException because myField is private. Is there a way to get/set private variables using reflection? (I've done it in C#, but this is the first time I've tried it in Java). If you're wondering why there is the need to do such madness :), it's because sometimes during unit testing it's handy to set private variables to bogus values for failure testing, etc.

解决方案

Figured it out. Need

field.setAccessible(true);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值