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 canonical name in java?
What are conditionals and its types?
Is null a string in java?
Why string is immutable with example?
Which graphs are functions?
What is this keyword used for?
Given a singly linked list, determine whether it contains a loop or not without using temporary space?
Difference between final and effectively final ?
Is main an identifier?
What about interthread communication and how it takes place in java?
Which arithmetic operations can result in the throwing of an arithmeticexception?
Can a class have multiple constructors?
Write a java program to generate fibonacci series ?
What are thread local variables?
Tell some latest versions in JAVA related areas?