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 are data types in programming?

776


What is the escape character in java?

743


What are strings in physics?

794


What is a Transient Object?

849


What is the use of inner class?

793


Difference between ‘>>’ and ‘>>>’ operators in java?

903


Can the garbage collection be forced by any means?

741


Can private class be extended java?

779


What is the purpose of a default constructor?

845


Define locale.

824


Can we execute java program without main method?

750


What is appletviewer?

821


What does singleton mean in java?

747


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).

1786


What is string english?

778