Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it allowed to access Java private fields via reflection?

Consider this example :

import java.lang.reflect.Field;  public class Test {      public static void main(String[] args) {         C c = new C();         try {             Field f = C.class.getDeclaredField("a");             f.setAccessible(true);             Integer i = (Integer)f.get(c);             System.out.println(i);         } catch (Exception e) {}     } }  class C {     private Integer a =6; } 

It seems illogical that you are allowed to access private fields of classes with reflection. Why is such a functionality available? Isn't it "dangerous" to allow such access?

like image 523
Savvas Dalkitsis Avatar asked Aug 06 '09 15:08

Savvas Dalkitsis


People also ask

Can java reflection API access private fields?

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.

Can we access private methods using reflection?

You can access the private methods of a class using java reflection package.

Why do we use java reflection?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

Is reflection safe java?

1 - Reflection (as a concept) is indeed orthogonal to safety/security. There was a big emphasis in the design of java to make it a safe platform, with static typing, security manager, disciplined usage of class loader, and no way to screw pointers/memory.


2 Answers

Private is intended to prevent accidental misuse, not as a security mechanism. If you choose to bypass it then you can do so at your own risk and the assumption you know what you are doing.

like image 89
jcoder Avatar answered Sep 18 '22 19:09

jcoder


Both getDeclaredField() and setAccessible() are actually checked by the security manager and will throw an exception when your code is not allowed to do this. More often than not you won't notice it, because Java code is often run without a security manager.

One important exception are Applets, which always run with a security manager.

like image 25
Joachim Sauer Avatar answered Sep 20 '22 19:09

Joachim Sauer