Can a class add a method to itself at runtime (like from a static
block), so that if someone is performing reflection on this class, they'll see the new method, even though it wasn't defined at compile time?
Background:
A framework I'm using expects Action
classes to be defined that have a doAction(...)
method, by convention. The framework inspects these classes at runtime to see what type of parameters are available in their doAction()
method. For example: doAction(String a, Integer b)
I'd like each class to be able to programatically generate its doAction()
method with various parameters, just-in-time when it is inspected. The body of the method can be empty.
I'm not sure that is possible. However, you could use AspectJ, ASM, etc. and weave these methods into the appropriate classes.
The other alternative is to use composition to wrap the target class and provide the doAction method. You would end up delegating to the target class in this case.
No, that is not (easily) possible in Java.
It sounds like you are trying to use Java as if it is a dynamic programming language. For example, Ruby has open classes: you can add and remove methods from Ruby classes at runtime. In Ruby, you can also have a "method missing" method in your class, that will be called when you try to call a method that doesn't exist in the class. Such a thing also doesn't exist in Java.
There is a version of Ruby that runs on the JVM, JRuby, and it has to do very difficult tricks to make open classes work on the JVM.
I've never tried anything quite like that myself, but you should have a look at ASM, cglib, and Javassist.
You can have a
doAction
method which does whatever you would like the generated method to do. Is there a reason it needs to be generated or can it be dynamic?