What are uses for reflection? (e.g the Java Reflection API)
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?
There are times when you want to have a library which can handle any data types without having to read the class files.
eg Serialization, database connectivity frameworks, dependency injection frameworks, frameworks which use annotations.
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.
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.
链接地址: http://www.djcxy.com/p/47616.html上一篇: Java中的反射api