views:

212

answers:

3

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!

A: 

You can refer a very nice IBM article "Functional programming in the Java language" (http ://www.ibm.com/developerworks/java/library/j-fp.html) which can give you inside-out with examples.

Green Techy
A: 

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

Michael Borgwardt
A: 

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.

MattChurchy