使用ASM访问一个类

使用ASM4可以方便的访问一个类文件结构内容,只需要实现ClassVisitor接口或继承ClassAdapter

注意,ASM基于责任链模式设计,有严格的访问顺序,如下:

visit visitSource? visitOuterClass? ( visitAnnotation | visitAttribute )*
( visitInnerClass | visitField | visitMethod )*
visitEnd

ASM会依次调用方法visit,visitSource...,"?"表示调用0次或一次,"*"表示调用多次。

下面看一个简单的访问过程:

public class ClassReaderExample {
	private static class MyClassVisitor implements ClassVisitor {
		@Override
		public void visit(int version, int access, String name,
				String signature, String superName, String[] interfaces) {
			
			System.out.println("class name:" + name);
			System.out.println("super class name:" + superName);
			System.out.println("class version:" + version);
			System.out.println("class access:" + access);
			System.out.println("class signature:" + signature);
			if (interfaces != null && interfaces.length > 0) {
				for (String str : interfaces) {
					System.out.println("implemented interface name:" + str);
				}
			}

		}

		@Override
		public void visitSource(String source, String debug) {
			System.out.println("source:"+source);
		}

		@Override
		public void visitOuterClass(String owner, String name, String desc) {
			System.out.println("owner:" + owner);
			System.out.println("outerName:" + name);
		}

		@Override
		public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
			return null;
		}

		@Override
		public void visitAttribute(Attribute attr) {
			System.out.println("attribute" + attr);
		}

		@Override
		public void visitInnerClass(String name, String outerName,
				String innerName, int access) {
			System.out.println("innerClass" + name);
		}

		@Override
		public FieldVisitor visitField(int access, String name, String desc,
				String signature, Object value) {
			System.out.println("field:" + name + ",access" + access + ",desc"+ desc);
			return null;
		}

		@Override
		public MethodVisitor visitMethod(int access, String name, String desc,
				String signature, String[] exceptions) {
			System.out.println("method:" + name + ",access" + access + ",desc" + desc);
			return null;
		}

		@Override
		public void visitEnd() {
			System.out.println("visitEnd");
		}
	}

	public static void main(String args[]) throws IOException {
		ClassReader classReader = new ClassReader("java.lang.String");
		classReader.accept(new MyClassVisitor(), 0);
	}
}

 

 

 

你可能感兴趣的:(bytecode)