我使用的是asm仪表库。使用visitVarInsn,我得到了一个局部变量的索引。我想使用索引并接收更多有用信息,如变量的名称和类型。你知道怎么做吗?谢谢。
发布于 2010-12-01 20:31:04
在LocalVariablesSorter.visitLocalVariable方法中获取它。
发布于 2012-06-14 19:43:08
我使用的代码如下:
private LocalVariableNode getLocalVariableNode(VarInsnNode varInsnNode, MethodNode methodNode) {
int varIdx = varInsnNode.var;
int instrIdx = getInstrIndex(varInsnNode);
List<?> localVariables = methodNode.localVariables;
for (int idx = 0; idx < localVariables.size(); idx++) {
LocalVariableNode localVariableNode = (LocalVariableNode) localVariables.get(idx);
if (localVariableNode.index == varIdx) {
int scopeEndInstrIndex = getInstrIndex(localVariableNode.end);
if (scopeEndInstrIndex >= instrIdx) {
// still valid for current line
return localVariableNode;
}
}
}
throw new RuntimeException("Variable with index " + varIdx + " and scope end >= " + instrIdx
+ " not found for method " + methodNode.name + "!");
}一般的问题是局部变量的索引可以重用。因此,您必须确保为给定的索引获取正确的LocalVariableNode。为此,您需要确保给定的变量在使用它的代码位置仍然有效。问题是您不能使用行号,因为
所以你需要使用指令索引,它总是正确的。而是AbstractInsnNode中不能从外部访问的内部信息。为了绕过这个问题,我使用了以下代码,它显然破坏了封装,并且由于许多原因而不被推荐。如果你想出更好的办法,让我知道!在此期间,这是可行的:
private int getInstrIndex(AbstractInsnNode insnNode) {
try {
Field indexField = AbstractInsnNode.class.getDeclaredField("index");
indexField.setAccessible(true);
Object indexValue = indexField.get(insnNode);
return ((Integer) indexValue).intValue();
} catch (Exception exc) {
throw new RuntimeException(exc);
}
}https://stackoverflow.com/questions/4324321
复制相似问题