java源码解析之qdox
前言
qdox可以将一个java源码解析成一个包含class的对象,通过这个对象我们可以获取所有方法,属性,方法参数,返回值,注释,tag等信息。
简单使用
待解析的源码如下
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
public class Client {
/**
* 读取文件内容并压缩
*
* @param filePath 文件路径
* @return 文件内容
*/
private static byte[] readFromFileAndCompress(String filePath) {
// test comment
int len = -1;
byte[] buf = new byte[1024];
try (InputStream input = new BufferedInputStream(new FileInputStream(filePath));
ByteArrayOutputStream output = new ByteArrayOutputStream();
DeflaterOutputStream dos = new DeflaterOutputStream(output)) {
while ((len = input.read(buf)) != -1) {
dos.write(buf, 0, len);
}
return output.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return new byte[0];
}
}
使用qdox解析
import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.DocletTag;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaMethod;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
public class Client {
public static void main(String[] args) throws IOException {
JavaProjectBuilder javaProjectBuilder = new JavaProjectBuilder();
javaProjectBuilder.addSource(new File("D:\\java\\decompile\\Client.java"));
Collection<JavaClass> classes = javaProjectBuilder.getClasses();
for (JavaClass aClass : classes) {
System.out.println("class name: " + aClass.getName());
for (JavaMethod classMethod : aClass.getMethods()) {
System.out.println("method name:" + classMethod.getName());
System.out.println("tags: ");
for (DocletTag docletTag : classMethod.getTags()) {
System.out.println(" " + docletTag.getName() + ": " + docletTag.getValue());
}
System.out.println("comment: " + classMethod.getComment());
}
}
}
}
输出为
class name: Client
method name:readFromFileAndCompress
tags:
param: filePath 文件路径
return: 文件内容
comment: 读取文件内容并压缩
获取了类名称,方法名称,方法标签,方法注释等信息。
maven的插件maven-javadoc-plugin中就使用到了qdox。