Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to do a static dispatch, bytecode generated proxy in java nowadays?

Tags:

java

bytecode

I have ued cglib in th epast, but frankly I have to believe there is a more convenient way than the callback array and callback filter approach in cglib. I know there used to be an aspectwerkz proxy,. but it seems to have wandered away somewhere.

like image 710
brianm Avatar asked Dec 05 '25 23:12

brianm


2 Answers

Javassist allows programming bytecode with using Java code snippets:

CtClass point = ClassPool.getDefault().get("Point");
CtMethod m = CtNewMethod.make(
             "public int xmove(int dx) { x += dx; }",
             point);
point.addMethod(m);
like image 186
Jevgeni Kabanov Avatar answered Dec 08 '25 13:12

Jevgeni Kabanov


If you just want simple proxies with minimal amount of mucking with bytecode, try janino ( http://docs.codehaus.org/display/JANINO/Home ):

final String bodyText=
"public Object get(Object obj) {return null;}\n"+
"public void set(Object obj, Object val) {}\n"+
"public Class getPropertyType() {return Void.class;}\n"+
"public boolean isPrimitive() {return true;}\n";

return (PropHandle)
   ClassBodyEvaluator.createFastClassBodyEvaluator(
   new Scanner(target+"__"+property, new StringReader(bodyText)),
   PropHandle.class, // Base type to extend/implement
   (ClassLoader)null); // Use current thread's context class loader

That's a snippet from my ORM which generates accessors.

If you really wish to work on byte-code level, try Javassist - it has fairly nice interface.

like image 24
Cyberax Avatar answered Dec 08 '25 12:12

Cyberax