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
Can you give names of Container classes?
Explain what do you mean by functional overloading in java?
How do you define a parameter?
When should I use singleton?
For class CFoo { }; what default methods will the compiler generate for you>?
How do you control extraneous variables?
What are the two types of java programming?
How can we create an immutable class in java?
What is class and its types?
What is hashmap in java?
What is the purpose of the main method?
What is difference between this and super keyword?
Is an object null?
Mention the default values of all the elements of an array defined as an instance variable.
Why is method overloading not possible by changing the return type in java?