public static InsnList forEach ( Variable counterVar , Variable arrayLenVar , InsnList array , InsnList action ) { Validate . notNull ( counterVar ) ; Validate . notNull ( arrayLenVar ) ; Validate . notNull ( array ) ; Validate . notNull ( action ) ; Validate . isTrue ( counterVar . getType ( ) . equals ( Type . INT_TYPE ) ) ; Validate . isTrue ( arrayLenVar . getType ( ) . equals ( Type . INT_TYPE ) ) ; InsnList ret = new InsnList ( ) ; LabelNode doneLabelNode = new LabelNode ( ) ; LabelNode loopLabelNode = new LabelNode ( ) ; // put zero in to counterVar ret . add ( new LdcInsnNode ( 0 ) ) ; // int ret . add ( new VarInsnNode ( Opcodes . ISTORE , counterVar . getIndex ( ) ) ) ; // // load array we'll be traversing over ret . add ( array ) ; // object[] // put array length in to arrayLenVar ret . add ( new InsnNode ( Opcodes . DUP ) ) ; // object[], object[] ret . add ( new InsnNode ( Opcodes . ARRAYLENGTH ) ) ; // object[], int ret . add ( new VarInsnNode ( Opcodes . ISTORE , arrayLenVar . getIndex ( ) ) ) ; // object[] // loopLabelNode: test if counterVar == arrayLenVar, if it does then jump to doneLabelNode ret . add ( loopLabelNode ) ; ret . add ( new VarInsnNode ( Opcodes . ILOAD , counterVar . getIndex ( ) ) ) ; // object[], int ret . add ( new VarInsnNode ( Opcodes . ILOAD , arrayLenVar . getIndex ( ) ) ) ; // object[], int, int ret . add ( new JumpInsnNode ( Opcodes . IF_ICMPEQ , doneLabelNode ) ) ; // object[] // load object from object[] ret . add ( new InsnNode ( Opcodes . DUP ) ) ; // object[], object[] ret . add ( new VarInsnNode ( Opcodes . ILOAD , counterVar . getIndex ( ) ) ) ; // object[], object[], int ret . add ( new InsnNode ( Opcodes . AALOAD ) ) ; // object[], object // call action ret . add ( action ) ; // object[] // increment counter var and goto loopLabelNode ret . add ( new IincInsnNode ( counterVar . getIndex ( ) , 1 ) ) ; // object[] ret . add ( new JumpInsnNode ( Opcodes . GOTO , loopLabelNode ) ) ; // object[] // doneLabelNode: pop object[] off of stack ret . add ( doneLabelNode ) ; ret . add ( new InsnNode ( Opcodes . POP ) ) ; // return ret ; }
For each element in an object array performs an action .