What Is Reflection and Why Is It Useful

What is reflection and why is it useful?

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

What exactly is Reflection and when is it a good approach?

Reflection is a facility where you can query an object about its attributes at runtime. For example, Python, Java and .Net have facilities where you can find the instance variables or methods of an object.

An example of an application for reflection is an O/R mapping layer. Some use reflection to construct an object by quering its properties at runtime and dynamically populating an instance. This allows you to do this programatically based on metadata from some sort of data dictionary without having to recompile the application.

To take a simple example, I'll use Python because its reflection facilities are very simple to use and involve less boilerplate than those of java or .Net.

ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class foo:
... def __init__(self):
... self.x = 1
...
>>> xx = foo() # Creates an object and runs the constructor
>>> xx.__dict__ # System metadata about the object
{'x': 1}
>>> a = xx.__dict__ # Now we manipulate the object through
>>> a['y'] = 2 # its metadata ...
>>> print xx.y # ... and suddenly it has a new instance variable
2
>>>

Now, we've used basic reflection to examine the instance variables of an arbitrary object. The special variable __dict__ on Python is a system property of an object that has a hash table of its members keyed by the variable (or method) name. We have reflectively examined the object and used the reflection facilities to artificially poke a second instance variable into it, which we can then display by invoking it as an instance variable.

Note that this particular trick doesn't work on Java or .Net, as the instance variables are fixed. The type system of these languages doesn't allow new instance variables to be added at runtime in the way that python's 'duck' typing system does. However, you could have reflectively updated the value of an instance variable that was declared in the type definition.

You can also use reflection to dynamically construct method invocations and perform various other neat tricks such as instantiating an object based on a parameter. For example, if you had some sort of plugin based system where certain capabilities were optional, you could use reflection to query the plugin about what services it offered (perhaps by querying whether certain interfaces were implemented) without requiring explicit metadata.

Many dynamic language interfaces such as OLE automation use reflection as an integral part of the interface.

Java: What scenarios call for the use of reflection?

Any time you're dealing with a string at runtime and want to treat part of that string as an identifier in the language.

  1. Remote procedure calling -- treat part of a message received over the network as a method name.
  2. Serialization and deserialization -- convert field names to string so you can write the object's fields to a stream and later convert it back into an object.
  3. Object-relational mappings -- maintain a relationship between fields in an object and columns in a database.
  4. Interfaces with dynamically typed scripting languages -- turn a string value produced by a scripting language into a reference to a field or method on an object.

It can also be used to allow language features to be emulated in the language.
Consider the command line java com.example.MyClass which turns a string into a class name. This doesn't require reflection, because the java executable can turn a .class file into code, but without reflection it would not be able to write java com.example.Wrapper com.example.MyClass where Wrapper delegates to its argument as in:

class Wrapper {
public static void main(String... argv) throws Exception {
// Do some initialization or other work.
Class<?> delegate = Class.forName(argv[0]);
Method main = delegate.getMethod("main", String[].class);
main.apply(null, Arrays.asList(argv).subList(1, argv.length).toArray(argv));
}
}

Why is the use of reflection in .NET recommended?

The main value of Reflection is that it can be used to inspect assemblies, types, and members. It's a very powerful tool for determining the contents of an unknown assembly or object and can be used in a wide variety of cases.

Opponents of Reflection will cite that it is slow, which is true when compared to static code execution--however Reflection is used throughout the .NET framework, and provided that it's not abused it can be a very powerful tool in the toolkit.

Some useful applications:

  • Determining dependencies of an assembly

  • Location types which conform to an interface, derive from a base / abstract class, and searching for members by attributes

  • (Smelly) testing - If you depend on a class which is untestable (ie it doesn't allow you to easily build a fake) you can use Reflection to inject fake values within the class--it's not pretty, and not recommended, but it can be a handy tool in a bind.

  • Debugging - dumping out a list of the loaded assemblies, their references, current methods, etc...

When is using reflection a good practice?

Reflection is a tool, you should use it when you need it, an use others where more appropriate.

When is appropriate to use reflection? When you are dealing with instance of object or classes which have some common behavior which is not enforced by interfaces.

The simplest example is POJO, you very often use classes which are just a collection of fields and their getter and setter, they much behave in the same manner, but you cannot define their common behavior with inheritance.

There are hundreds of tools that leverage that behavior building pojos from scratch, or setting fields, and they use reflection.

Examples: GSON, JAXB, Hibernate, Spring, Weld ... etc.

Reflection is more difficult to write, more difficult to debug, and test, give you pretty scary and uninformative stack traces, but let you deal with more general common behavior then inheritance.

A side note, since the introduction of annotations reflection has become less scary, because you can decorate classes with information that let you do reflection with a more reliable approach, in fact all the framework I cited use annotations.

Last but not least, you don't use reflection much all the same, because you need it for meta programming and, most of the time, meta programming has been done for you by others (see GSON, JAXB, Hibernate, Spring, Weld ... etc), so in fact you will find difficult to find a problem general enough to be solved with reflection, and has not been solved by others.

Is reflection useful for Android?

Reflection (in every languages) is very powerful.

In Android most of time reflection is not needed, because you can find Security Exceptions, problems. It depends on what You do.

If you use undocumented classes, libs, you can use it, and it's very useful.

Sometimes, to do particular things, like turn on/off 3g on old device, change device language, you need rooted device to use reflection.

Finally, depends always on what You do.

What is Reflection in Java Can anyone explain?

Reflection is the process of examining or modifying the runtime behavior of a class at runtime. It is used in:

• IDE (Integreted Development Environment) e.g. Eclipse, MyEclipse, NetBeans.

• Debugger

• Test Tools etc.

What are uses for reflection? (e.g the Java Reflection API)

There are times when you want to have a library which can handle any data types without having to read the class files.

e.g. Serialization, database connectivity frameworks, dependency injection frameworks, frameworks which use annotations.

Reflection: Effective, Awesome, Necessary uses

No, reflection does not directly enable a class to change its code. However, there are some awesome things you can do with java.lang.reflect.Proxy - e.g. write generic code that implements any JavaBean-style interface (i.e. set and get methods), or even code that implements any interface by having all methods return default values - possibly even recursively, i.e. methods that return an interface type return an object that behaves in the same way.

This facility is used by Mock object libraries, and probably most prominently by the Groovy language to implement a fully dynamic language that supports duck typing and monkey patching.



Related Topics



Leave a reply



Submit