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


Please Help Members By Posting Answers For Below Questions

what is recursion in java

590


What is close method? How it's different from Finalize & Dispose?

553


Why is inheritance used in java?

595


Which is easier netbeans or eclipse?

602


What is flag in java?

527






Can we use return in constructor?

483


What are data structures in java?

525


What’s a deadlock?

602


What is passing parameters in java?

509


Difference between method overloading and overriding.

575


Can we make main() thread as daemon?

568


What is size () in java?

538


What is a flag value?

510


what methods would you overwrite in java.lang.object class?

558


Why you should not use singleton?

534