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.
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.
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).
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 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.
Figured it out. Need
field.setAccessible(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With