Besides the bytecode development libraries, if you have an interface for your class, you can use the Java Proxy class.
With interface:
public interface Foo { void bar(); }
Specific class:
class FooImpl { public void bar() { System.out.println("foo bar"); } }
To handle invoked methods, you use the InvocationHandler :
class FooInvocationHandler implements InvocationHandler { private Foo foo; FooInvocationHandler(Foo foo) { this.foo = foo; } public Object invoke(Object proxy, Method method, Object[] args) throws Exception { if (method.getName().equals("bar")) System.out.println("foo me");
Then create a FooFactory to create and migrate 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 will wrap the FooImpl object so that it:
Foo foo = FooFactory.createFoo(...); foo.bar();
Print
foo me foo bar
It is an alternative to BCEL libraries that can do this and more, including creating classes from runtime information, but BCEL libraries are not native. ( Proxy is in java.lang.reflect from everything starting from 1.3.)
Brian source share