我想获取给定MethodDeclaration对象的java方法签名的字节码。我正在使用Eclipse jdt解析Java类,并像下面这样遍历MethodDeclaration:
private static void processJavaFile(String javaFilePath) {
List<MethodDeclaration> methodDeclarations = new ArrayList<MethodDeclaration>();
FileInputStream reader = null;
try {
File javaFile = new File(javaFilePath);
reader = new FileInputStream(javaFile);
byte[] bs = new byte[reader.available()];
reader.read(bs, 0, reader.available());
String javaContent = new String(bs);
CompilationUnit unit = ASTUtil.getCompilationUnit(javaContent, 4);
MethodVisitor methodVisitor = new MethodVisitor();
unit.accept(methodVisitor);
methodDeclarations = methodVisitor.getMethods();
for (MethodDeclaration methodDeclaration :methodDeclarations){
////////////////////////////////////////////////////////////////////////
// ???? I want to get the byte code of the method signature here ???? //
////////////////////////////////////////////////////////////////////////
}
} catch (Exception e) {
e.printStackTrace();
}
}
最佳答案
MethodDeclaration
实例是AST的一部分,代表源代码的语法。它需要解析源代码中找到的类型名称,然后才能为方法创建签名。
for (MethodDeclaration methodDeclaration :methodDeclarations){
// the next line requires that the project is setup correctly
IMethodBinding resolved = methodDeclaration.resolveBinding();
// then you can create a method signature
ITypeBinding[] pType = resolved.getParameterTypes();
String[] pTypeName=new String[pType.length];
for(int ix = 0; ix < pType.length; ix++)
pTypeName[ix]=pType[ix].getBinaryName().replace('.', '/');
String rTypeName=resolved.getReturnType().getBinaryName().replace('.', '/');
//org.eclipse.jdt.core.Signature
String signature = Signature.createMethodSignature(pTypeName, rTypeName);
System.out.println(signature);
}