views:

59

answers:

7

Reflection can be used to access just about any object's internals, which is kind of not cool. I tried to list the legitimate uses of it, but in the end only serialization came to my mind.

What other (legitimate) uses can you find to using reflection in order to access otherwise inaccessible members?

EDIT I mean stuff you can't do if you don't have reflection.

+1  A: 

Unit testing comes to mind. If you want to test a private method but not expose it or use the InternalsVisibleToAttribute.

Oded
+1  A: 

One is persisting objects to a DB. E.g. Hibernate does use reflection, and in some cases e.g. the object's ID might be a private member, with private setter/getter, because it is of no use in the Java domain. However it is needed in the DB, so Hibernate sets/gets it in the background, and uses it for determining object identity.

Another is writing the initial unit tests for badly designed legacy code, where you can't just start refactoring since you have no unit tests to safeguard yourself. In such cases, if other means (described in Working Effectively with Legacy Code) can't help you, reflection may be the last resort to start working towards maintainable code.

Péter Török
A: 

Profiling or monitoring can be useful reasons to use reflection to private members and functions. For example, if you want to know how often a database connection is actually made, you can monitor access to a private SqlConnection.

This can better be done with AOP, but, if trying to get AOP to be acceptable is too difficult politically, then reflection can help out while you are in development.

James Black
How can you monitor access to a field through reflection? Have I missed something?
zneak
You may want to look here: http://www.ibm.com/developerworks/library/j-dyn0603/, the entire series may be of interest. Depending on your interests/needs, you could create a new class, such as what Spring does for AOP, as JDK6 allows you to compile classes you create on the fly.
James Black
A: 

You can also use reflection to invoke the methods based upon input type parameter ( like enum), thus essentially replacing a switch statement.

for example:

enter code here

   public class Test
   {
    public enum Status
    {
      Add,
      Delete,
      Update
    }

    public void Save(Status status)
    {
          //use reflection to obtain corresponding method
           MethodInfo method = this.GetType().GetMethod(status.ToString(),BindingFlags.NonPublic | BindingFlags.Instance);
         //Invoke method here

    }
    //you don't want to expose these methods
    private void Add()
    {

    }
    private void Delete()
    {

    }
    private void Update()
    {

    }
}
akapoor
_Or_ you can make a delegate dictionary and achieve the same effect without reflection.
zneak
A: 

Debugging and profiling come to mind immediately -- they need to be able to get a more complete view of the internals of objects.

Garbage collection is another -- yes, the JVM has a garbage collector built in, but someone has to write that code and while most JVMs aren't written in java, there's no reason they couldn't be.

Chris Dodd
Though, I'd be surprised if debuggers and profilers did use reflection. They probably do it a much weirder way since they're not part of the monitored process. And I don't think garbage collection is often implemented using reflection either; that would probably be a massive waste of resources (compared to what you could do with compiler support).
zneak
I don't buy your 2nd paragraph. If Garbage Collection was *reified* and running at the same level as the applicative code that might be the case, but otherwise, even if a JVM is written in Java (metacircularity), the Garbage Collection is not happening at the same meta level as the applicative code.
ewernli
A: 

Here is another one: You are creating some kind of editor, and would like to easily expose parameters. Ie. automatically create UI elements.

Cornelius Scarabeus
That probably doesn't mean "accessing private members".
zneak
True. I started thinking of legitimate uses of reflection and forgot the original question.
Cornelius Scarabeus
+1  A: 

I guess one big area where it is used is in the context of managed environment, that is, when an framework or environment is supposed to provide some facilities and might require to access to private data.

Public/private access modifier is a concern at the application design level and a field shouldn't be turned public for the sake of making a framework happy. Examples include then framework like Hibernate which manages object persistence, dependency injection framework which can inject data in private field, or more generally application server which work regardless of the access modifier.

Even more generally, this fall into the umbrella of meta-programming. Some code inspects and modifies other objects dynamically without knowing their structure upfront.

ewernli
+1 for DI - noone else (including me) mentioned that :-)
Péter Török