gpt4 book ai didi

java - 如何获取java MethodDeclaration对应的Byte code

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:28 25 4
gpt4 key购买 nike

我想获取给定 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);
}

关于java - 如何获取java MethodDeclaration对应的Byte code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18943361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com