一.简介
最近项目中需要分析java文件中依赖的类、Jar包中class文件扫描,通过提取字节码文件中的Constant_Class_info 常量池中的信息实现class 文件依赖分析。使用了ASM 轻量级jar包读取字节码文件,根据JVM虚拟机规范解析常量池信息。
字节码文件类型描述:
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>8.0</version>
</dependency>
二.实现
import org.objectweb.asm.ClassReader;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ClassUtil {
/**
* 分析class 文件中Constant_Class_info 信息
* @param classStream
* @return
* @throws IOException
*/
public static List<String> constClassInfo(InputStream classStream) throws IOException {
ClassReader reader = new ClassReader(classStream);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
List<String> infos = new ArrayList<>();
for(int i=1;i<reader.getItemCount();i++) {
int off = reader.getItem(i);
if(off > 0 && reader.readByte(off-1) == 7){
int index = reader.readUnsignedShort(off);
off = reader.getItem(index);
int len = reader.readUnsignedShort(off);
for(int j=0;j<len;j++){
int b = reader.readByte(off+2+j);
bos.write(b);
}
infos.add(bos.toString("utf-8"));
bos.reset();
}
}
return infos;
}
/**
* 分析class 文件中Constant_Utf8_info 常量池信息项
* @param classStream class 字节码流
* @throws IOException
*/
public static List<String> constUtf8Info(InputStream classStream) throws IOException