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

Can you give names of Container classes?

1862


Explain what do you mean by functional overloading in java?

557


How do you define a parameter?

585


When should I use singleton?

523


For class CFoo { }; what default methods will the compiler generate for you>?

622






How do you control extraneous variables?

510


What are the two types of java programming?

539


How can we create an immutable class in java?

585


What is class and its types?

546


What is hashmap in java?

573


What is the purpose of the main method?

545


What is difference between this and super keyword?

521


Is an object null?

563


Mention the default values of all the elements of an array defined as an instance variable.

526


Why is method overloading not possible by changing the return type in java?

597