java - What is reflection and why is it useful?

ID : 319

viewed : 287

Tags : javareflectionterminologyjava





Top 5 Answer for java - What is reflection and why is it useful?

vote vote

94

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++

vote vote

90

Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

For example, all objects in Java have the method getClass(), which lets you determine the object's class even if you don't know it at compile time (e.g. if you declared it as an Object) - this might seem trivial, but such reflection is not possible in less dynamic languages such as C++. More advanced uses lets you list and call methods, constructors, etc.

Reflection is important since it lets you write programs that do not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

Lots of modern frameworks use reflection extensively for this very reason. Most other modern languages use reflection as well, and in scripting languages (such as Python) they are even more tightly integrated, since it feels more natural within the general programming model of those languages.

vote vote

72

One of my favorite uses of reflection is the below Java dump method. It takes any object as a parameter and uses the Java reflection API to print out every field name and value.

import java.lang.reflect.Array; import java.lang.reflect.Field;  public static String dump(Object o, int callCount) {     callCount++;     StringBuffer tabs = new StringBuffer();     for (int k = 0; k < callCount; k++) {         tabs.append("\t");     }     StringBuffer buffer = new StringBuffer();     Class oClass = o.getClass();     if (oClass.isArray()) {         buffer.append("\n");         buffer.append(tabs.toString());         buffer.append("[");         for (int i = 0; i < Array.getLength(o); i++) {             if (i < 0)                 buffer.append(",");             Object value = Array.get(o, i);             if (value.getClass().isPrimitive() ||                     value.getClass() == java.lang.Long.class ||                     value.getClass() == java.lang.String.class ||                     value.getClass() == java.lang.Integer.class ||                     value.getClass() == java.lang.Boolean.class                     ) {                 buffer.append(value);             } else {                 buffer.append(dump(value, callCount));             }         }         buffer.append(tabs.toString());         buffer.append("]\n");     } else {         buffer.append("\n");         buffer.append(tabs.toString());         buffer.append("{\n");         while (oClass != null) {             Field[] fields = oClass.getDeclaredFields();             for (int i = 0; i < fields.length; i++) {                 buffer.append(tabs.toString());                 fields[i].setAccessible(true);                 buffer.append(fields[i].getName());                 buffer.append("=");                 try {                     Object value = fields[i].get(o);                     if (value != null) {                         if (value.getClass().isPrimitive() ||                                 value.getClass() == java.lang.Long.class ||                                 value.getClass() == java.lang.String.class ||                                 value.getClass() == java.lang.Integer.class ||                                 value.getClass() == java.lang.Boolean.class                                 ) {                             buffer.append(value);                         } else {                             buffer.append(dump(value, callCount));                         }                     }                 } catch (IllegalAccessException e) {                     buffer.append(e.getMessage());                 }                 buffer.append("\n");             }             oClass = oClass.getSuperclass();         }         buffer.append(tabs.toString());         buffer.append("}\n");     }     return buffer.toString(); } 
vote vote

63

Uses of Reflection

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

Extensibility Features

An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names. Class Browsers and Visual Development Environments A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code. Debuggers and Test Tools Debuggers need to be able to examine private members in classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to ensure a high level of code coverage in a test suite.

Drawbacks of Reflection

Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

  • Performance Overhead

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, 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.

  • Security Restrictions

Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

  • Exposure of Internals

Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

source: The Reflection API

vote vote

52

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

Top 3 video Explaining java - What is reflection and why is it useful?







Related QUESTION?