概述
读取一个类的信息可以使用反射,但是在效率上,ASM比反射更快。
一、导入依赖
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.2</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-util</artifactId>
<version>9.2</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-commons</artifactId>
<version>9.2</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-tree</artifactId>
<version>9.2</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-analysis</artifactId>
<version>9.2</version>
</dependency>
二、要被ASM读取类信息的User.class
public class User<T> {
private Integer a = 1;
private Integer c;
private String b = "123";
private List<Integer> list;
private User user;
private T data;
}
三、读取类信息
public class ReaderClassField {
public static void main(String[] args) throws IOException {
ClassReader classReader = new ClassReader(User.class.getName());
SimpleClassVisitor simpleClassVisitor = new SimpleClassVisitor(Opcodes.ASM5);
ClassNode classNode = new ClassNode();
classReader.accept(simpleClassVisitor,0);
}
}
class SimpleClassVisitor extends ClassVisitor{
public SimpleClassVisitor(int i) {
super(i);
}
@Override
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()+", access:"+access+", name:"+name+", desc:"+desc+", signature:"+signature+", value:"+value);
return super.visitField(access, name, desc, signature, value);
}
}
打印结果 可以看到字段信息被读出来了。
|