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?
Answers were Sorted based on User's Feedback
Answer / 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 |
Answer / puneet
This is a compile time activities, the scopes and the access
issues are handled at the compile time and this exception is
not the subclas of the runtime exception class and doesnt go
unchecked during compile time, they are checked at compile
time and the compile time exceptions are checked exceptions
which are checked by the compiler before hand and the
example of runtime exception is say bad logic like array
having -ve size and division by zero where actual excecution
occurs in JRE of the byte code.
Is This Answer Correct ? | 4 Yes | 0 No |
Answer / chaitali
No,we cannot access private data outside of class in java.
There is only compile time checking and no runtime check in
java because Java supports concepts like Polymorphism and
reflection where on runtime certain decisions are taken
Is This Answer Correct ? | 14 Yes | 14 No |
What steps are taken when the OS shifts from one-thread execution to another?
What is Generic in java? Where can we write Generic ( class or method or objects or etc...)? with simple example? Thanks, Bose.
2 Answers Infosys, Tech Mahindra,
What is public static void main?
What is a compilation unit?
How do weakhashmap works?
When you declare a method as abstract method ?
What are the differences between path and classpath variables?
Is integer immutable in java?
What are the types of sockets in java?
What is parsing a string?
In how many ways we can create threads in java?
Can java inner class be static?