What is reflection and why is it useful?

前端 未结 21 2886
春和景丽
春和景丽 2020-11-21 04:36

What is reflection, and why is it useful?

I\'m particularly interested in Java, but I assume the principles are the same in any language.

21条回答
  •  野性不改
    2020-11-21 04:57

    From java documentation page

    java.lang.reflect package provides classes and interfaces for obtaining reflective information about classes and objects. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use of reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.

    AccessibleObject allows suppression of access checks if the necessary ReflectPermission is available.

    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

    It includes following functionality.

    1. Obtaining Class objects,
    2. Examining properties of a class (fields, methods, constructors),
    3. Setting and getting field values,
    4. Invoking methods,
    5. Creating new instances of objects.

    Have a look at this documentation link for the methods exposed by Class class.

    From this article (by Dennis Sosnoski, President, Sosnoski Software Solutions, Inc) and this article (security-explorations pdf):

    I can see considerable drawbacks than uses of using Reflection

    User of Reflection:

    1. It provides very versatile way of dynamically linking program components
    2. It is useful for creating libraries that work with objects in very general ways

    Drawbacks of Reflection:

    1. Reflection is much slower than direct code when used for field and method access.
    2. It can obscure what's actually going on inside your code
    3. It bypasses the source code can create maintenance problems
    4. Reflection code is also more complex than the corresponding direct code
    5. It allows violation of key Java security constraints such as data access protection and type safety

    General abuses:

    1. Loading of restricted classes,
    2. Obtaining references to constructors, methods or fields of a restricted class,
    3. Creation of new object instances, methods invocation, getting or setting field values of a restricted class.

    Have a look at this SE question regarding abuse of reflection feature:

    How do I read a private field in Java?

    Summary:

    Insecure use of its functions conducted from within a system code can also easily lead to the compromise of a Java security model. So use this feature sparingly

提交回复
热议问题