What is reflection and why is it useful?

前端 未结 21 2811
春和景丽
春和景丽 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条回答
  •  -上瘾入骨i
    2020-11-21 04:59

    Reflection is an API which is used to examine or modify the behaviour of methods, classes, interfaces at runtime.

    1. The required classes for reflection are provided under java.lang.reflect package.
    2. Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.
    3. Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.

    The java.lang and java.lang.reflect packages provide classes for java reflection.

    Reflection can be used to get information about –

    1. Class The getClass() method is used to get the name of the class to which an object belongs.

    2. Constructors The getConstructors() method is used to get the public constructors of the class to which an object belongs.

    3. Methods The getMethods() method is used to get the public methods of the class to which an objects belongs.

    The Reflection API is mainly used in:

    IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
    Debugger and Test Tools etc.

    Advantages of Using Reflection:

    Extensibility Features: An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.

    Debugging and testing tools: Debuggers use the property of reflection to examine private members on classes.

    Drawbacks:

    Performance Overhead: Reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

    Exposure of Internals: Reflective code breaks abstractions and therefore may change behaviour with upgrades of the platform.

    Ref: Java Reflection javarevisited.blogspot.in

提交回复
热议问题