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 are data types in programming?
What is the escape character in java?
What are strings in physics?
What is a Transient Object?
What is the use of inner class?
Difference between ‘>>’ and ‘>>>’ operators in java?
Can the garbage collection be forced by any means?
Can private class be extended java?
What is the purpose of a default constructor?
Define locale.
Can we execute java program without main method?
What is appletviewer?
What does singleton mean in java?
take an array with -ve and +ve value both.find out the nearest value of 0(zero).if two values are same like(-2 and +2)then extract +2 is nearest of 0(zero).
What is string english?