What is reflection and why is it useful?

前端 未结 21 2877
春和景丽
春和景丽 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

    0 讨论(0)
  • 2020-11-21 04:58

    The name reflection is used to describe code which is able to inspect other code in the same system (or itself).

    For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.

    So, to give you a code example of this in Java (imagine the object in question is foo) :

    Method method = foo.getClass().getMethod("doSomething", null);
    method.invoke(foo, null);
    

    One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.

    There are some good reflection examples to get you started at http://docs.oracle.com/javase/tutorial/reflect/index.html

    And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common.

    Update from a comment:

    The ability to inspect the code in the system and see object types is not reflection, but rather Type Introspection. Reflection is then the ability to make modifications at runtime by making use of introspection. The distinction is necessary here as some languages support introspection, but do not support reflection. One such example is C++

    0 讨论(0)
  • 2020-11-21 04:59

    Reflection is a key mechanism to allow an application or framework to work with code that might not have even been written yet!

    Take for example your typical web.xml file. This will contain a list of servlet elements, which contain nested servlet-class elements. The servlet container will process the web.xml file, and create new a new instance of each servlet class through reflection.

    Another example would be the Java API for XML Parsing (JAXP). Where an XML parser provider is 'plugged-in' via well-known system properties, which are used to construct new instances through reflection.

    And finally, the most comprehensive example is Spring which uses reflection to create its beans, and for its heavy use of proxies

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-21 05:01

    Reflection is a set of functions which allows you to access the runtime information of your program and modify it behavior (with some limitations).

    It's useful because it allows you to change the runtime behavior depending on the meta information of your program, that is, you can check the return type of a function and change the way you handle the situation.

    In C# for example you can load an assembly (a .dll) in runtime an examine it, navigating through the classes and taking actions according to what you found. It also let you create an instance of a class on runtime, invoke its method, etc.

    Where can it be useful? Is not useful every time but for concrete situations. For example you can use it to get the name of the class for logging purposes, to dynamically create handlers for events according to what's specified on a configuration file and so on...

    0 讨论(0)
  • 2020-11-21 05:01

    As I find it best to explain by example and none of the answers seem to do that...

    A practical example of using reflections would be a Java Language Server written in Java or a PHP Language Server written in PHP, etc. Language Server gives your IDE abilities like autocomplete, jump to definition, context help, hinting types and more. In order to have all tag names (words that can be autocompleted) to show all the possible matches as you type the Language Server has to inspect everything about the class including doc blocks and private members. For that it needs a reflection of said class.

    A different example would be a unit-test of a private method. One way to do so is to create a reflection and change the method's scope to public in the test's set-up phase. Of course one can argue private methods shouldn't be tested directly but that's not the point.

    0 讨论(0)
提交回复
热议问题