Reflection: Effective, Awesome, Necessary uses

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

So I've read the Reflection tutorial on Java's website, and I think I generally understand that it allows a class to inspect itself, having access to properties, methods, etc. However, how, if at all, does this relate to mutable or immutable code? Can classes change their own code using something like reflection? If not, what's the most awesome use of reflection you've come across/created?

Thanks!


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 - eg write generic code that implements any JavaBean-style interface (ie set and get methods), or even code that implements any interface by having all methods return default values - possibly even recursively, ie 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.


Java reflection does not allow you to dynamically change the code of the program like you would be able to in a dynamic language such as ruby.

Java reflection allows you to see meta data regarding methods and properties of a class. It also allows you to call those methods or to change values of properties, without having prior knowledge of the methods and properties available.

To modify program code at runtime in Java, have a look at Aspect-Oriented Programming.

The most awesome use i've seen is in the JRuby bindings, to make Java classes dynamically available as ruby code. I've also used reflection myself to allow me look up error codes from a third party library that was using static int Constants instead of enums.

链接地址: http://www.djcxy.com/p/47620.html

上一篇: 什么是Java中的反射任何人都可以解释吗?

下一篇: 反思:有效,真棒,必要的用途