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 the synonym of string?
Does it matter in what order catch statements for filenotfoundexception and ioexception are written?
what is the role of xml in core java?? and how we can use it?? can somebody give a sample program with explanation and from where i can read more about xml?????
Tell us something about different types of casting?
Do I need java on my pc?
What is keyword in oop?
How many types of threads are there in java?
Explain the difference between extends thread vs implements runnable in java?
java Technical questions asked by JPMC
How do you trim a space in java?
How does regex work?
What is the use of optional ?
How do you check if a number is a perfect square?
How destructors are defined in java?
what is instanceof operator used in java?