简体   繁体   中英

java runtime class generation frameworks

I want to have one feature of Java 8 for Java 7: automatic interface implementation generation for method (to avoid performace deficiency due to reflection calls). I know that Java 8 provide the generation at compile time but I think it's not possible for Java 7 (without maintainance of metadata files). So I agree with implementation generation at runtime.

Example:

I have following interface:

public interface Extractor<E> {
  public Object getProperty(E aSourceObject);
}

And a bean class (or interface)

public class Foo {
  public int getProperty1();
  public String getProperty2();
  public boolean getProperty3();
}

I need for each property of Foo an implementation of Extractor interface. Something like Foo::getProperty1 for Java 8.

public class Foo1Extractor implements Extractor<Foo> {
  public Object getProperty(Foo anObject) {
    return anObject.getProperty1();
  }
}

Should I use JavaCompiler (currently I have few interfaces to implement and can work with template classes) or you have better solutions?

The main requirement is the short bytecode generation time and LGPL compatibility (can be used in commercial product).

If possible, provide a little example for my case.

You may not see visible performance improvement if you replace reflection with generated classes unless your application is performing millions operation per second. Also the complexity of adding the dynamic code generation to the project (both in runtime and compile time) are quite high. So I'd recommend to go for it only if reflection is proved to be the real bottleneck.

Anyway, for the code generation in compile time in JDK 7 you can the use the annotation processing API , which is basically a plugin API for javac that you can combine it with some sort of template engine. Have a look at this project which uses the power of the annotation processing for doing quite good stuff.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM