0

I was just thinking and I wondered: since access control is only meant to provide protection against accident and not against fraud I was wondering if it is possible to access the values of hidden variables in Java?

Take for example

public Cat {

public int numberOfLegs = 4;
private int numberOfWhiskers = 42;

}

Is it possible to find the value of numberOfWhiskers from outside of this class?

Edit: I have read the thread in the link and I can see that by using SetAccesible() you can obtain the value of any private field you know the name of. Can we find the value of a field of which we do not know the name?

Note: this can be done in some languages such as C++ for example by use of pointers iterating across fields in the class.

phcoding
  • 608
  • 4
  • 16
  • I somewhat disagree with your premise. Java is, in fact, designed to afford the VM protection from untrusted code running within it. That is what the security manager and the security model is designed to do. Access controls are an integral part of the security model, and are validated at runtime, they are not merely used during compile time. – Dilum Ranatunga Apr 02 '13 at 22:37

1 Answers1

3

You can use reflection to bypass the private check. Use the Class#getDeclaredField method, and the Field#getInt method (there are other accessors).

This code can be in another class:

Cat myCat = new Cat();
int whiskers;

try
{
    Field field = Cat.class.getDeclaredField("numberOfWhiskers");
    // This line bypasses the private control
    field.setAccessible(true);
    whiskers = field.getInt(myCat);
}
catch (NoSuchFieldException e) { /* Handle */ }
catch (IllegalAccessException e) { /* Handle */ }

EDIT

I've seen the link to the duplicate question. I must agree, normally, don't do this.

SECOND EDIT

In response to the additional edited question, you can use the Class#getDeclaredFields method to return a Field[] with which you can use to iterate over all the fields of the class.

Field[] fields = Cat.class.getDeclaredFields();
// Iterate over the array here.
rgettman
  • 176,041
  • 30
  • 275
  • 357