Synthesis of new methods at runtime in Java?

Possible duplicate:
Can a Java class add a method in time?

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

+1
source share
2 answers

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"); // 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 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.)

+2
source

In an already loaded class? As I know.

However, you may be interested in creating a new class. I see two options:

  • I recently created a project that generated a String-based class containing code, and loaded it into the system and executed it with the main method. However, this requires the JDK to be installed = very unreliable
  • Via BCEL. It also has flaws, but seems to be better overall. This requires that you use the method bytecode in advance. Now you can do some cheats, for example using the method

So:

 public static void printTest() { System.out.println("Hey!"); } 

And then take a look at the bytecode, seeing where in hell ConstantPool! saved, and then takes the bytecode for the method, caches it into an array of bytes, then dynamically creates the method with predefined bytes + a constant pool (which you examined earlier) and changing the constant in your line. This would be very difficult, although for more complex methods (Note: the same thing could be done to change the method that it calls, or the field that it receives, for example, to change to err)

Since there are actually no good options, I see that these are your best bets.

+3
source

All Articles