Wednesday, November 22, 2006

Compile Time Reflection

I want compile time reflection in Java. They came close with giving me this:
Class someClass=MyObject.class

But, I wish it went further. If you're going to make me go through the pain of verifying everything at compile-time, then make my life easier for example:
try {
Method method=MyObject.class.getDeclaredMethod("doSomethingCool", AnotherObject.class, String.class);
} catch(NoSuchMethodException problem) {
//handle reflection exception that could have been caught at compile-time
} catch(SecurityException problem) {
//handle reflection exception that could have been caught at compile-time
}

Right now, if I mis-typed "doSomethingCool" then it wouldn't get caught until run-time.Now, we don't want to make the baby Gosling cry, do we? How about this:
Method method=MyObject.class.doSomethingCool(AnotherObject,String);

For one, it's more succint and no need for any try/catch blocks because the compiler did all of the work. Another nice side effect is that you can check regular visibility constraints (if I call the above in MyObject and doSomethingCool is private, then all is good. Otherwise, don't allow it if outside of MyObject). Now, I don't have to set the setAccessible() method on Method and no security check. Now, of course, you can also use this for fields as well. In fact, it's simpler.

Now, I ask since they gave us ".class", why didn't they finish the job? Java reflection has always seemed half way there to me.

Just don't get me started on JavaBeans (where are the collections?).

1 comment:

Anonymous said...

A couple of years ago at Colorado Software Summit, Sun was soliciting feedback on what we'd like added to the language. One of the things I asked for was a ".method" syntax just as you're proposing. They seemed receptive to the idea but I haven't heard anything back since then.