1

Possible Duplicate:
What is reflection, and why is it useful?

So I've been messing with the Reflection API lately, and it seems cool to screw around with here and there but what exactly is the use of it?

You see, it's all fun to get field/method names and return types and set accessibility and whatnot, but how could this [reflection] possibly be of any use if you can read the java file/class with your own eyes?

Maybe I'm really ignorant or I don't understand the full concept of this Reflection thingy, but could you explain to me in what ways this could be helpful?

Community
  • 1
  • 1
ZimZim
  • 3,291
  • 10
  • 49
  • 67
  • Imagine a serialization framework that takes a "POJO" and turns it into JSON or XML. (These exist). A structure can be dynamically determined (with or without annotations) just by "poking around" even if passing in an `Object`: in short, it's for doing things *in an automated fashion* without having to account for a particular compile-time type. –  Mar 21 '12 at 19:15

3 Answers3

4

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

I have used it to generate keys and values from an object I did not have access to change.

So if you have a large codebase and a team "owns" a class you need to use, but it's really set in stone. That is, no further changes, and you really need to convert it to your own format, than doing it manually, which is tiresome, so what you can do is get the fields name and its value and according to your rules put it in your own object.

Anuj Balan
  • 7,629
  • 23
  • 58
  • 92
rapadura
  • 5,242
  • 7
  • 39
  • 57
0

Reflection is used with generics. This way one piece of code can handle a multiplicity of types of objects.

It is also used when you don't necessarily have access to the java file but want to know something specific about it, usually in a troubleshooting effort.

Travis J
  • 81,153
  • 41
  • 202
  • 273