Can we access private data outside of the class directly in
java programming language? Why There is no runtime checking
in java, which leads to access the private data directly
outside of a class?
Answer Posted / gaurav sehra
Using reflection we can see\access private data or private method of a class
u can try the below code and will easily see the desired result :-
import java.lang.reflect.Field;
class SimpleKeyPair {
private String privateKey = "India"; // private field
}
public class PrivateMemberAccessTest {
public static void main(String[] args) throws Exception {
SimpleKeyPair keyPair = new SimpleKeyPair();
Class c = keyPair.getClass();
// get the reflected object
Field field = c.getDeclaredField("privateKey");
// set accessible true
field.setAccessible(true);
System.out.println("Value of privateKey: " + field.get(keyPair)); // prints "Tokyo"
// modify the member varaible
field.set(keyPair, "Bharat");
System.out.println("Value of privateKey: " + field.get(keyPair)); // prints "Berlin"
}
}
Is This Answer Correct ? | 7 Yes | 1 No |
Post New Answer View All Answers
what is recursion in java
What is close method? How it's different from Finalize & Dispose?
Why is inheritance used in java?
Which is easier netbeans or eclipse?
What is flag in java?
Can we use return in constructor?
What are data structures in java?
What’s a deadlock?
What is passing parameters in java?
Difference between method overloading and overriding.
Can we make main() thread as daemon?
What is size () in java?
What is a flag value?
what methods would you overwrite in java.lang.object class?
Why you should not use singleton?