views:

216

answers:

9

I was just curious, why should we use reflection in the first place?

// Without reflection
Foo foo = new Foo();
foo.hello();

// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);

We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?

To make everything dynamic?

+8  A: 

Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.

The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.

As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.

Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.

Jon Skeet
Why was this downvoted?
SLaks
+1, as it is so.
Thorbjørn Ravn Andersen
@Jon: isn't this a duplicate?
John Saunders
@John: Could be. To be honest I'm pretty weak at finding duplicates.
Jon Skeet
@All I love StackOverflow! :)
zengr
+3  A: 

A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.

deamon
A: 

in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.

Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first

Thorbjørn Ravn Andersen
A: 

It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.

dan04
+3  A: 

You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.

The most common applications are probably these three:

  • Serialization (see, e.g., .NET's XmlSerializer)
  • Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
  • Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
brone
+1  A: 

Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.

e.g. JXPath allows you to navigate objects like this:

//company[@name='Sun']/address

so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.

You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.

Brian Agnew
+3  A: 

It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.

Also, many frameworks use reflection to analyze and use your objects. For example:

  • hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
  • you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
  • parsing annotations is done by reflection
Bozho
+1  A: 

I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.

This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).

After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.

Windle
A: 

some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.

Parth