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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1771744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:28:29  来源:igfitidea点击:

Accessing private variables in Java via reflection

javareflection

提问by dcp

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 IllegalAccessExceptionbecause myFieldis 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.

我得到一个IllegalAccessException因为myField是私人的。有没有办法使用反射来获取/设置私有变量?(我已经在 C# 中完成了它,但这是我第一次在 Java 中尝试它)。如果您想知道为什么需要这样做:),那是因为有时在单元测试期间,将私有变量设置为用于故障测试等的虚假值很方便。

采纳答案by dcp

Figured it out. Need

弄清楚了。需要

field.setAccessible(true);