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 use of bufferedreader?
What is a cup of java?
How can we make string upper case or lower case?
What are thread local variables?
What is derived datatype?
what is an objects lock and which objects have locks? : Java thread
Is java se open source?
Why is stringbuffer not immutable?
Describe the Big-O Notation.
Which class is the superclass of all classes?
What methods are used in Servlet?Applet communication?
What do you mean by chromounits in java8?
Define Multiprogramming and Multiprocessing in java.
Is there any way to find whether software installed in the
system is registered by just providing the .exe file?
I have tried the following code but its just displaying the
directory structure in the registry.
Here the code :
package com.msi.intaller;
import java.util.Iterator;
import ca.beq.util.win32.registry.RegistryKey;
import ca.beq.util.win32.registry.RootKey;
public class RegistryFinder {
public static void main(String... args) throws Exception
{
RegistryKey.initialize(RegistryFinder.class.getResource("jRe
gistryKey.dll").getFile());
RegistryKey key = new RegistryKey(RootKey.HKLM,
"Software\\ODBC");
for (Iterator
What is this keyword used for?