//constructor and fields public void generate(Assignment assignment) { String varName = assignment.getVarName(); Expression expression = assignment.getExpression(); Type type = expression.getType(); if(scope.isLocalVariableExists(varName)) { int index = scope.getLocalVariableIndex(varName); methodVisitor.visitVarInsn(type.getStoreVariableOpcode(), index); return; } Field field = scope.getField(varName); String descriptor = field.getType().getDescriptor(); methodVisitor.visitVarInsn(Opcodes.ALOAD,0); expression.accept(expressionGenerator); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD,field.getOwnerInternalName(),field.getName(),descriptor); }
如果局部变量和字段名字冲突了,那么局部变量有更高的优先级。
PUTFIELD 和 GETFIELD 相似,但是会出栈顶数据,表达式的值会被赋值到变量
示例
如下 Enkel 文件
1 2 3 4 5 6 7 8 9
Fields {
int field
start { field = 5 print field } }
生成字节码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class Fields { public int field;
public void start(); Code: 0: aload_0 //get "this" 1: ldc #9 // load constant "5" from constant pool 3: putfield #11 // Field field:I - pop 5 off the stack and write to field 6: getstatic #17 // Field java/lang/System.out:Ljava/io/PrintStream; 9: aload_0 //get "this" reference 10: getfield #11 // Field field:I 13: invokevirtual #22 // Method "Ljava/io/PrintStream;".println:(I)V 16: return