Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am new to Java; through my studies, I read that reflection is used to invoke classes and methods, and to know which methods are implemented or not.

When should I use reflection, and what is the difference between using reflection and instantiating objects and calling methods the traditional way?

share|improve this question
5  
Check out stackoverflow.com/questions/37628/… –  Jalayn Dec 8 '11 at 8:47
8  
Please do your share of research before posting. There is lots of material on StackExchange (as @Jalayn noted) and the web in general about reflection. I suggest you read e.g. the Java Tutorial on Reflection and come back after that if you have any more concrete questions. –  Péter Török Dec 8 '11 at 8:49
1  
There has got to be a million dupes. –  DeadMG Dec 8 '11 at 8:53
1  
More than a few professional programmers would answer "as rarely as possible, maybe even never." –  Ross Patterson Apr 2 '13 at 23:30

5 Answers 5

up vote 16 down vote accepted
  • Reflection is much slower than just calling methods by their name, because it has to inspect the metadata in the bytecode instead of just using precompiled addresses and constants.

  • Reflection is also more powerful: you can retrieve the definition of a protected or final member, remove the protection and manipulate it as if it had been declared mutable! Obviously this subverts many of the guarantees the language normally makes for your programs and can be very, very dangerous.

  • And this pretty much explains when you would use it. Ordinarily, don't. If you want to call a method, just call it. If you want to mutate a member, just declare it mutable instead of going behind the compile's back.

One useful real-world use of reflection is when writing a framework that has to interoperate with user-defined classes, where th framework author doesn't know what the members (or even the classes) will be. Reflection allows them to deal with any class without knowing it in advance. For instance, I don't think it would be possible to write a complex aspect-oriented librory without reflection.

As another example, JUnit used to use a trivial bit of reflection: it enumerates all methods in your class, assumes that all those called testXXX are test methods, and executes only those. But this can now be done better with annotations instead, and in fact JUnit 4 has largely moved to annotations instead.

share|improve this answer
3  
"More powerful" needs care. You don't need reflection to get Turing completeness, so no computation ever needs reflection. Of course Turing complete says nothing about other kinds of power, like I/O capabilities and, of course, reflection. –  Steve314 Dec 8 '11 at 9:11
1  
Reflection is not necessarily "much slower". You can use reflection once to generate a direct calling wrapper bytecode. –  SK-logic Dec 8 '11 at 10:57
    
You'll know it when you need it. I often wondered why (outside of language generation) one would need it. Then, suddenly, I did... Had to walk up and down parent/child chains to peek/poke data when I got panels from other devs to pop into one of the systems I maintain. –  Brian Knoblauch Dec 8 '11 at 13:41
    
@SK-logic: actually for generating bytecode you don't need reflection at all (indeed reflection contains no API for bytecode manipulation at all!). –  Joachim Sauer Oct 22 '12 at 11:19
    
@JoachimSauer, of course, but you'll need a reflection API to load this generated bytecode. –  SK-logic Oct 22 '12 at 15:29

Reflection allows a program to work with code that may not be present and do so in a reliable way.

"Normal code" have snippets like URLConnection c = null which by its sheer presence cause the class loader to load the URLConnection class as part of loading this class, throwing a ClassNotFound exception and exiting.

Reflection allow you to load classes based on their names in string form and test them for various properties (useful for multiple versions outside your control) before launching actual classes that depend on them. A typical example is the OS X specific code used to make Java programs look native under OS X, which are not present on other platforms.

share|improve this answer

I was like you once, I didn't know much about reflection - still don't - but I did use it once.

I had a class with two inner classes, and each class had lots of methods.

I needed to invoke all of the methods in the inner class, and invoking them manually would've been too much work.

Using reflection, I could invoke all these methods in just 2-3 lines of code, instead of the number of the methods themselves.

share|improve this answer
1  
Why the downvote? –  Mahmoud Hossam Dec 15 '11 at 7:58

I'd group uses of reflection into three groups:

  1. Instantiating arbitrary classes. For example, in a dependency injection framework, you probably declare that interface ThingDoer is implemented by the class NetworkThingDoer. The framework would then find the constructor of NetworkThingDoer and instantiate it.
  2. Marshalling and unmarshalling to some other format. For example, mapping an object with getters and settings that follow the bean convention to JSON and back again. The code doesn't actually know the names of the fields or the methods, it just examines the class.
  3. Wrapping a class in a layer of redirection (perhaps that List isn't actually loaded, but just a pointer to something that knows how to fetch it from the database) or faking a class entirely (jMock will create a synthetic class that implements an interface for testing purposes).
share|improve this answer

Reflection can automatically keep parts of your program in sync, where previously, you would have had to manually update your program to use the new interfaces.

share|improve this answer
2  
The price you pay in this case is that you lose type-checking by the compiler and refactor-safety in the IDE. It's a trade-off that I'm not willing to make. –  Barend Jan 6 '12 at 9:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.