Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java private field access possible when having a reference?

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?

like image 488
asenovm Avatar asked Oct 27 '11 13:10

asenovm


People also ask

Can you access private fields in java?

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.

Is it possible to get information about private fields methods using reflection?

Yes it is possible.

Can java reflection API access private fields and methods of a class?

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.

How do you access a private field in another class?

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.


2 Answers

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.

like image 106
Michael Borgwardt Avatar answered Oct 24 '22 03:10

Michael Borgwardt


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.
  • ...
like image 31
Xavi López Avatar answered Oct 24 '22 03:10

Xavi López