Frank Frank - 1 month ago 5
Java Question

Synthesizing new methods at runtime in Java?

Possible Duplicate:

Can a Java class add a method to itself at runtime?

Is it possible to synthesize a new method at runtime for a class in Java? Is there a library to make that possible?


Beyond bytecode engineering libraries, if you have an interface for your class, you could use Java's Proxy class.

With an interface:

public interface Foo {
    void bar();

The concrete class:

class FooImpl implements Foo {
    public void bar() {
        System.out.println("foo bar");

To process the methods called, you use InvocationHandler:

class FooInvocationHandler implements InvocationHandler {

    private Foo foo;

    FooInvocationHandler(Foo foo) { = foo;

    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
        if (method.getName().equals("bar"))
            System.out.println("foo me");
            // return null if you don't want to invoke the method below
        return method.invoke(foo, args); // Calls the original method

Then create a FooFactory to generate and wrap FooImpl instances using Proxy:

public class FooFactory {
    public static Foo createFoo(...) {
        Foo foo = new FooImpl(...);
        foo = Proxy.newProxyInstance(Foo.class.getClassLoader(),
                new Class[] { Foo.class },
                new FooInvocationHandler(foo));
        return foo;

This would wrap the FooImpl object so that this:

Foo foo = FooFactory.createFoo(...);;


foo me
foo bar

This is an alternative to the BCEL libraries, which can do this and a lot more, including generating classes from runtime information, but the BCEL libraries aren't native. (Proxy is in java.lang.reflect on everything since 1.3.)