I came across the following "strange" feature today - if you have a reference to an object from the class A in the body of the class A you can access the private fields of this object - i.e:
public class Foo{
private int bar;
private Foo foo;
public void f()
{
if(foo.bar == bar) // foo.bar is visible here?!
{
//
}
}
}
Anyone has a good explanation about this?
If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.
Yes it is possible.
Despite the common belief it is actually possible to access private fields and methods of other classes via Java Reflection. It is not even that difficult. This can be very handy during unit testing.
By using Public Method We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.
Access modifiers work at the class level, not at the instance level: all code in the same class can access private members of all instances of the class.
Nothing particularly strange about it.
It is intended to be this way.
Citing the Java Language Specification:
A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
- ...
- (Otherwise,) if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member.
- ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With