【发布时间】:2015-08-28 23:31:18
【问题描述】:
我想使用 ASM 库来创建能够在运行时返回常量值的字节码方法。我可以使用的 ASM 中的一类是 LdcInsnNode。所以我的示例代码是:
class Myclass{
final const Object value;
@Override
public MethodNode get(String clsName, String mhName){
int access = Opcodes.ACC_PUBLIC| Opcodes.ACC_STATIC;
MethodNode methodNode = new MethodNode(ASM5, access, mhName, type.toString(), null, null);
methodNode.instructions.add(new LdcInsnNode(value));
Type returnType = Type.getReturnType(type.toMethodDescriptorString());
if(!returnType.getInternalName().equals(Type.getDescriptor(value.getClass))){
methodNode.instructions.add(new TypeInsnNode(Opcodes.CHECKCAST, returnType.getInternalName()));
}
methodNode.instructions.add(new InsnNode(Opcodes.ARETURN));
return new methodNode;
}
}
我的问题是当它是复杂类型的实例(用户定义的类)时如何加载值。 LdcInsnNode 的文档只说:
/** * 要加载到堆栈上的常量。此参数必须为非 null * {@link Integer}、{@link Float}、{@link Long}、{@link Double}、a * {@link String} 或 {@link org.objectweb.asm.Type}。
public LdcInsnNode(final Object cst) {
super(Opcodes.LDC);
this.cst = cst;
}
【问题讨论】:
标签: bytecode java-bytecode-asm bytecode-manipulation