Reputation: 728
I want to create an object of a class, and override some of it's methods. eg:
Foo bar = new Foo(){
public void fighters(){
//some stuff
}
};
The problem is: the name of the class is stored in a String. My obvious move was to create a new instance using the Constructor.newInstance(Object o) method, like this:
Class c = cl.loadClass("com.pom.Foo");
Foo f = (Foo) (c.getDeclaredConstructor(String.class).newInstance("Hello!"));
Although this piece of code successfully creates a new instance of the class, I don't know how to override it's methods now.
Any suggestions?
Upvotes: 3
Views: 3180
Reputation: 3053
I think you have a few options, none of them nice and all stink to high heaven of an architectural issue with how you're addressing the problem you're presented with.
Delegating Wrapper
Create a DelegaingFoo class that looks like this:
class DelegatingFoo {
Callable callMe;
public DelegatingFoo(Callable callMe) {
this.callMe = callMe;
}
public void fighters(){
calLMe.call();
}
};
Instanciate this instead, passing in a Callable object into the constructor as you are above. this disjoints the code you want to run from the bit that injects it.
Use a JVM language
Compile to something that can be run through javax.script, such as BeanShell, Groovy, etc. Depending on what you're ultimately doing, this may be a viable option.
Customised Classloader
If you have the option of using an alternative class loader (which presents it's own issues), which is something that would be fraught with it's own issues, and create something really quite complex. If you decide to consider this seriously, then looking at something like the OSGi class loading framework may give you some clues (it may even, at a stretch, be suitable).
Bytecode Manipulation
There are a few libraries which will help with bytecode munging / interception / generation / alteration on the fly:
WARNING
It should be noted that all the above are hacks, with increasing depravity as you go down them. I would get my architecture peer reviewed ASAP as I would put money on there being a cleaner & clearer approach to what you're doing.
Remember, code you write should be easier to read - otherwise you're creating a maintenance headache for yourself (or future project owners).
Upvotes: 2