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
Explain about main thread in java?
Which variables are stored in heap?
What are annotations in java?
Is java a software?
What is polymorphism java example?
Difference between static synchronization vs. Instance synchronization?
What is variable length arguments in java?
Can a private method be declared as static?
What exceptions occur during serialization?
Can we have a method name same as class name in java?
What is return in java?
What is the purpose of the wait(), notify(), and notifyall() methods in java programming?
Which variable is the independent variable?
Can a main method be declared final?
what is singleton in java?