通过反射访问Java中的私有变量 [英] Accessing private variables in Java via reflection

查看:229
本文介绍了通过反射访问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);
    }
}

所以说我这样做:

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

我收到 IllegalAccessException 因为 myField 是私有的。有没有办法使用反射获取/设置私有变量? (我是用C#完成的,但这是我第一次用Java编写它)。如果你想知道为什么需要做这样的疯狂:),这是因为有时在单元测试期间将私有变量设置为失败测试的伪值等是很方便的。

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.

推荐答案

想出来。需要

field.setAccessible(true);

这篇关于通过反射访问Java中的私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆