简体   繁体   English

是否可以通过反射调用私有属性或方法

[英]Is it possible to invoke private attributes or methods via reflection

I was trying to fetch the value of an static private attribute via reflection, but it fails with an error. 我试图通过反射获取静态私有属性的值,但它失败并出现错误。

Class class = home.Student.class;
Field field = studentClass.getDeclaredField("nstance");
Object obj = field.get(null);

The exception I get is: 我得到的例外是:

java.lang.IllegalAccessException: Class com.test.ReflectionTest can not access a member of class home.Student with modifiers "private static".

Moreover, there is a private I need to invoke, with the following code. 此外,我需要使用以下代码调用私有。

Method method = studentClass.getMethod("addMarks");
method.invoke(studentClass.newInstance(), 1);

but the problem is the Student class is a singleton class, and constructor in private, and cannot be accessed. 但问题是Student类是单例类,而构造函数是私有的,无法访问。

您可以设置可访问的字段:

field.setAccessible(true);

Yes it is. 是的。 You have to set them accessible using setAccessible(true) defined in AccesibleObject that is a super class of both Field and Method 您必须使用AccesibleObject中定义的setAccessible(true)设置它们是可访问的, AccesibleObjectFieldMethod的超类

With the static field you should be able to do: 使用静态字段,您应该能够:

Class class = home.Student.class;
Field field = studentClass.getDeclaredField("nstance");
field.setAccessible(true); // suppress Java access checking
Object obj = field.get(null); // as the field is a static field  
                              // the instance parameter is ignored 
                              // and may be null. 
field.setAccesible(false); // continue to use Java access checking

And with the private method 并使用私有方法

Method method = studentClass.getMethod("addMarks");
method.setAccessible(true); // exactly the same as with the field
method.invoke(studentClass.newInstance(), 1);

And with a private constructor: 并使用私有构造函数:

Constructor constructor = studentClass.getDeclaredConstructor(param, types);
constructor.setAccessible(true);
constructor.newInstance(param, values);

Yes, you can "cheat" like this: 是的,你可以像这样“欺骗”:

    Field somePrivateField = SomeClass.class.getDeclaredField("somePrivateFieldName");
    somePrivateField.setAccessible(true); // Subvert the declared "private" visibility
    Object fieldValue = somePrivateField.get(someInstance);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM