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

后端 未结 7 1919
暗喜
暗喜 2020-12-08 04:14

Consider this example :

import java.lang.reflect.Field;

public class Test {

    public static void main(String[] args) {
        C c = new C();
        try         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 04:33

    From the description of the java.lang.reflect package:

    Classes in this package, along with java.lang.Class accommodate applications such as debuggers, interpreters, object inspectors, class browsers, and services such as Object Serialization and JavaBeans that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class.

    Reflection provides a mechanism for accessing information about classes through means which are usually not available by regular interaction between classes and objects. One of such is allowing access to private fields from outside classes and objects.

    Yes, reflection in general can indeed be dangerous, as it can expose the internals of classes and objects.

    However, it also is a very powerful tool that can be used to inspect the internals of classes and objects, which can't be accessed by other standard means.

提交回复
热议问题