三、ASM 我们知道Java是静态语言,而python、ruby是动态语言,Java程序一旦写好很难在运行时更改类的行为,而python、ruby可以。 不过基于bytecode层面上我们可以做一些手脚,来使Java程序多一些灵活性和Magic,ASM就是这样一个应用广泛的开源库。
ASM is a Java bytecode manipulation framework. It can be used to dynamically generate stub classes or other proxy classes, directly in binary form, or to dynamically modify classes at load time, i.e., just before they are loaded into the Java Virtual Machine.
ASM完成了BCEL和SERP同样的功能,但ASM 只有30多k,而后两者分别是350k和150k。apache真是越来越过气了。
让我们来看一个ASM的简单例子Helloworld.java,它生成一个Example类和一个main方法,main方法打印"Hello world!"语句:
代码
-
import java.io.FileOutputStream;
-
import java.io.PrintStream;
-
-
import org.objectweb.asm.ClassWriter;
-
import org.objectweb.asm.MethodVisitor;
-
import org.objectweb.asm.Opcodes;
-
import org.objectweb.asm.Type;
-
import org.objectweb.asm.commons.GeneratorAdapter;
-
import org.objectweb.asm.commons.Method;
-
-
public class Helloworld extends ClassLoader implements Opcodes {
-
- public static void main(final String args[]) throws Exception {
-
-
-
-
- ClassWriter cw = new ClassWriter(0);
- cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null);
- MethodVisitor mw = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null,
- null);
- mw.visitVarInsn(ALOAD, 0);
- mw.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
- mw.visitInsn(RETURN);
- mw.visitMaxs(1, 1);
- mw.visitEnd();
- mw = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main",
- "([Ljava/lang/String;)V", null, null);
- mw.visitFieldInsn(GETSTATIC, "java/lang/System", "out",
- "Ljava/io/PrintStream;");
- mw.visitLdcInsn("Hello world!");
- mw.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println",
- "(Ljava/lang/String;)V");
- mw.visitInsn(RETURN);
- mw.visitMaxs(2, 2);
- mw.visitEnd();
- byte[] code = cw.toByteArray();
- FileOutputStream fos = new FileOutputStream("Example.class");
- fos.write(code);
- fos.close();
- Helloworld loader = new Helloworld();
- Class exampleClass = loader
- .defineClass("Example", code, 0, code.length);
- exampleClass.getMethods()[0].invoke(null, new Object[] { null });
-
-
-
-
-
- cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
- cw.visit(V1_1, ACC_PUBLIC, "Example", null, "java/lang/Object", null);
- Method m = Method.getMethod("void <init> ()");
- GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null,
- cw);
- mg.loadThis();
- mg.invokeConstructor(Type.getType(Object.class), m);
- mg.returnValue();
- mg.endMethod();
- m = Method.getMethod("void main (String[])");
- mg = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw);
- mg.getStatic(Type.getType(System.class), "out", Type
- .getType(PrintStream.class));
- mg.push("Hello world!");
- mg.invokeVirtual(Type.getType(PrintStream.class), Method
- .getMethod("void println (String)"));
- mg.returnValue();
- mg.endMethod();
- cw.visitEnd();
- code = cw.toByteArray();
- loader = new Helloworld();
- exampleClass = loader.defineClass("Example", code, 0, code.length);
- exampleClass.getMethods()[0].invoke(null, new Object[] { null });
- }
- }
我们看到上面的例子分别使用ASM的MethodVisitor和GeneratorAdapter两种方式来动态生成Example类并调用打印语句。
四、cglib cglib is a powerful, high performance and quality Code Generation Library, It is used to extend JAVA classes and implements interfaces at runtime. cglib是Code Generation Library的缩写。 cglib依赖于ASM库。 Hibernate主要是利用cglib生成pojo的子类并override get方法来实现lazy loading机制,Spring则是利用cglib来实现动态代理。 而JDK的动态代理机制要求有接口才行,这样就强制我们的pojo实现某个接口。 这里还是提供一个cglib的入门级的示例: MyClass.java:
代码
-
public class MyClass {
-
- public void print() {
- System.out.println("I'm in MyClass.print!");
- }
-
- }
Main.java:
代码
-
import java.lang.reflect.Method;
-
import net.sf.cglib.proxy.Enhancer;
-
import net.sf.cglib.proxy.MethodInterceptor;
-
import net.sf.cglib.proxy.MethodProxy;
-
-
public class Main {
-
- public static void main(String[] args) {
-
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(MyClass.class);
- enhancer.setCallback(new MethodInterceptorImpl());
- MyClass my = (MyClass) enhancer.create();
- my.print();
- }
-
- private static class MethodInterceptorImpl implements MethodInterceptor {
- public Object intercept(Object obj, Method method, Object[] args,
- MethodProxy proxy) throws Throwable {
-
- System.out.println(method + " intercepted!");
-
- proxy.invokeSuper(obj, args);
- return null;
- }
- }
- }
打印结果为:
代码
-
public void MyClass.print() intercepted!
- I'm in MyClass.print!
这个示例就基本上实现了日志AOP的功能 |
|