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 difference between object oriented programming language and object based programming language?
What is meant by bytecode?
Can string be considered as a keyword?
Howto get an object that will perform date & time calculations then format it for output in some different locales with different date style.can ne1 tel me the answer of this question.pls
What happens when heap memory is full?
What is callable java?
how can you take care of mutual exclusion using java threads? : Java thread
Tell us something about set interface.
How do you create a reference in java?
What is the difference between serializable and externalizable interface?
Can final class have constructor?
What is meant by tab pans?
Why do we need hashmap in java?
What is tree in java?
How can a gui component handle its own events?