Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private variables in Java via reflection [duplicate]

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.

like image 355
dcp Avatar asked Nov 20 '09 16:11

dcp


People also ask

Can we access private variable using reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

Can you access private variables in the same class?

This is perfectly legal. Objects of the same type have access to one another's private variables. This is because access restrictions apply at the class or type level (all instances of a class) rather than at the object level (this particular instance of a class).

How can I access private variable from another package?

We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class. Example: using System; using System.

Can we access private variable in child class using super?

Can you access a private variable from the superclass using the super keyword within the subclass? No. Private variables are only accessible to the class members where it belongs.


1 Answers

Figured it out. Need

field.setAccessible(true); 
like image 64
dcp Avatar answered Oct 06 '22 23:10

dcp