List of usage examples for org.objectweb.asm.commons GeneratorAdapter putField
public void putField(final Type owner, final String name, final Type type)
From source file:co.cask.cdap.internal.io.DatumWriterGenerator.java
License:Apache License
/** * Generates the constructor. The constructor generated has signature {@code (Schema, FieldAccessorFactory)}. *///from www. j a v a 2 s .c om private void generateConstructor() { Method constructor = getMethod(void.class, "<init>", Schema.class, FieldAccessorFactory.class); // Constructor(Schema schema, FieldAccessorFactory accessorFactory) GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, constructor, null, null, classWriter); // super(); // Calling Object constructor mg.loadThis(); mg.invokeConstructor(Type.getType(Object.class), getMethod(void.class, "<init>")); // if (!SCHEMA_HASH.equals(schema.getSchemaHash().toString())) { throw IllegalArgumentException } mg.getStatic(classType, "SCHEMA_HASH", Type.getType(String.class)); mg.loadArg(0); mg.invokeVirtual(Type.getType(Schema.class), getMethod(SchemaHash.class, "getSchemaHash")); mg.invokeVirtual(Type.getType(SchemaHash.class), getMethod(String.class, "toString")); mg.invokeVirtual(Type.getType(String.class), getMethod(boolean.class, "equals", Object.class)); Label hashEquals = mg.newLabel(); mg.ifZCmp(GeneratorAdapter.NE, hashEquals); mg.throwException(Type.getType(IllegalArgumentException.class), "Schema not match."); mg.mark(hashEquals); // this.schema = schema; mg.loadThis(); mg.loadArg(0); mg.putField(classType, "schema", Type.getType(Schema.class)); // For each record field that needs an accessor, get the accessor and store it in field. for (Map.Entry<TypeToken<?>, String> entry : fieldAccessorRequests.entries()) { String fieldAccessorName = getFieldAccessorName(entry.getKey(), entry.getValue()); classWriter.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL, fieldAccessorName, Type.getDescriptor(FieldAccessor.class), null, null); // this.fieldAccessorName // = accessorFactory.getFieldAccessor(TypeToken.of(Class.forName("className")), "fieldName"); mg.loadThis(); mg.loadArg(1); mg.push(entry.getKey().getRawType().getName()); mg.invokeStatic(Type.getType(Class.class), getMethod(Class.class, "forName", String.class)); mg.invokeStatic(Type.getType(TypeToken.class), getMethod(TypeToken.class, "of", Class.class)); mg.push(entry.getValue()); mg.invokeInterface(Type.getType(FieldAccessorFactory.class), getMethod(FieldAccessor.class, "getFieldAccessor", TypeToken.class, String.class)); mg.putField(classType, fieldAccessorName, Type.getType(FieldAccessor.class)); } mg.returnValue(); mg.endMethod(); }
From source file:co.cask.cdap.internal.io.FieldAccessorGenerator.java
License:Apache License
private void initializeReflectionField(GeneratorAdapter mg, Field field) { /*/*from w ww .j a v a2 s.co m*/ Save the reflected Field object for accessing private field. try { Field field = Fields.findField(classType, "fieldName"); field.setAccessible(true); this.field = field; } catch (Exception e) { throw Throwables.propagate(e); } */ Label beginTry = mg.newLabel(); Label endTry = mg.newLabel(); Label catchHandle = mg.newLabel(); mg.visitTryCatchBlock(beginTry, endTry, catchHandle, Type.getInternalName(Exception.class)); mg.mark(beginTry); // Field field = Fields.findField(classType, "fieldName") mg.loadArg(0); mg.push(field.getName()); mg.invokeStatic(Type.getType(Fields.class), getMethod(Field.class, "findField", java.lang.reflect.Type.class, String.class)); mg.dup(); // field.setAccessible(true); mg.push(true); mg.invokeVirtual(Type.getType(Field.class), getMethod(void.class, "setAccessible", boolean.class)); // this.field = field; // need to swap the this reference and the one in top stack (from dup() ). mg.loadThis(); mg.swap(); mg.putField(Type.getObjectType(className), "field", Type.getType(Field.class)); mg.mark(endTry); Label endCatch = mg.newLabel(); mg.goTo(endCatch); mg.mark(catchHandle); int exception = mg.newLocal(Type.getType(IllegalAccessException.class)); mg.storeLocal(exception); mg.loadLocal(exception); mg.invokeStatic(Type.getType(Throwables.class), getMethod(RuntimeException.class, "propagate", Throwable.class)); mg.throwException(); mg.mark(endCatch); }
From source file:co.cask.cdap.internal.io.FieldAccessorGenerator.java
License:Apache License
/** * Generates a setter that set the value by directly accessing the class field. * @param field The reflection field object. *//*from www . jav a 2 s .c o m*/ private void directSetter(Field field) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, getMethod(void.class, "set", Object.class, Object.class), setterSignature(), new Type[0], classWriter); // Simply access by field // ((classType)object).fieldName = (valueType)value; mg.loadArg(0); mg.checkCast(Type.getType(field.getDeclaringClass())); mg.loadArg(1); if (field.getType().isPrimitive()) { mg.unbox(Type.getType(field.getType())); } else { mg.checkCast(Type.getType(field.getType())); } mg.putField(Type.getType(field.getDeclaringClass()), field.getName(), Type.getType(field.getType())); mg.returnValue(); mg.endMethod(); }
From source file:co.cask.cdap.internal.io.FieldAccessorGenerator.java
License:Apache License
/** * Generates the primitive setter (setXXX) based on the field type. * @param field The reflection field object. *//*from www.j a va 2s .c om*/ private void primitiveSetter(Field field) { String typeName = field.getType().getName(); String methodName = String.format("set%c%s", Character.toUpperCase(typeName.charAt(0)), typeName.substring(1)); GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, getMethod(void.class, methodName, Object.class, field.getType()), null, new Type[0], classWriter); if (isPrivate) { // set the value using the generic void get(Object, Object) method with boxing the value. mg.loadThis(); mg.loadArgs(); mg.valueOf(Type.getType(field.getType())); mg.invokeVirtual(Type.getObjectType(className), getMethod(void.class, "set", Object.class, Object.class)); } else { // Simply access the field. mg.loadArg(0); mg.checkCast(Type.getType(field.getDeclaringClass())); mg.loadArg(1); mg.putField(Type.getType(field.getDeclaringClass()), field.getName(), Type.getType(field.getType())); } mg.returnValue(); mg.endMethod(); }
From source file:co.cask.common.internal.io.FieldAccessorGenerator.java
License:Apache License
private void initializeReflectionField(GeneratorAdapter mg, Field field) { /*//from ww w. ja v a2 s. c o m Save the reflected Field object for accessing private field. try { Field field = Fields.findField(classType, "fieldName"); field.setAccessible(true); this.field = field; } catch (Exception e) { throw Throwables.propagate(e); } */ Label beginTry = mg.newLabel(); Label endTry = mg.newLabel(); Label catchHandle = mg.newLabel(); mg.visitTryCatchBlock(beginTry, endTry, catchHandle, Type.getInternalName(Exception.class)); mg.mark(beginTry); // Field field = findField(classType, "fieldName") mg.loadArg(0); mg.push(field.getName()); mg.invokeStatic(Type.getType(Fields.class), getMethod(Field.class, "findField", TypeToken.class, String.class)); mg.dup(); // field.setAccessible(true); mg.push(true); mg.invokeVirtual(Type.getType(Field.class), getMethod(void.class, "setAccessible", boolean.class)); // this.field = field; // need to swap the this reference and the one in top stack (from dup() ). mg.loadThis(); mg.swap(); mg.putField(Type.getObjectType(className), "field", Type.getType(Field.class)); mg.mark(endTry); Label endCatch = mg.newLabel(); mg.goTo(endCatch); mg.mark(catchHandle); int exception = mg.newLocal(Type.getType(IllegalAccessException.class)); mg.storeLocal(exception); mg.loadLocal(exception); mg.invokeStatic(Type.getType(Throwables.class), getMethod(RuntimeException.class, "propagate", Throwable.class)); mg.throwException(); mg.mark(endCatch); }
From source file:com.changingbits.Builder.java
License:Apache License
/** Increments counts as field members (count0, count1, * ...) instead of a this.intArray[0], ... */ private void buildCounterAsm2(GeneratorAdapter gen, Node node, boolean sawOutputs) { sawOutputs |= node.outputs != null;// w w w . j a v a2 s.c o m if (node.left != null) { assert node.left.end + 1 == node.right.start; // Recurse on either left or right Label labelLeft = new Label(); Label labelEnd = new Label(); gen.loadArg(0); gen.push(node.left.end); gen.ifCmp(Type.LONG_TYPE, GeneratorAdapter.LE, labelLeft); buildCounterAsm2(gen, node.right, sawOutputs); gen.goTo(labelEnd); gen.visitLabel(labelLeft); buildCounterAsm2(gen, node.left, sawOutputs); gen.visitLabel(labelEnd); } else if (sawOutputs) { // leaf: this.countN++ gen.loadThis(); gen.loadThis(); gen.getField(COMPILED_COUNTER_CLASS2_TYPE, "count" + node.leafIndex, Type.INT_TYPE); gen.push(1); gen.visitInsn(Opcodes.IADD); gen.putField(COMPILED_COUNTER_CLASS2_TYPE, "count" + node.leafIndex, Type.INT_TYPE); } }
From source file:com.changingbits.Builder.java
License:Apache License
public LongRangeCounter getCounter2() { finish(false);/* w w w. j a va2 s . c o m*/ // Maps each range to the leaf counts that contribute to it: Map<Integer, List<Integer>> rangeToLeaf = new HashMap<>(); buildRangeToLeaf(root, new ArrayList<Integer>(), rangeToLeaf); StringBuilder sb = new StringBuilder(); sb.append('\n'); sb.append("public void add(long v) {\n"); int count = 0; for (LongRange range : ranges) { sb.append(" // range "); sb.append(count++); sb.append(": "); sb.append(range); sb.append('\n'); } buildJavaCounter2Source(root, 1, sb, false); sb.append("}\n\n"); sb.append("public int[] getCounts() {\n"); sb.append(" int[] counts = new int["); sb.append(ranges.length); sb.append("];\n"); for (int range = 0; range < ranges.length; range++) { List<Integer> elements = rangeToLeaf.get(range); if (elements != null) { sb.append(" counts["); sb.append(range); sb.append("] = count"); sb.append(elements.get(0)); for (int i = 1; i < elements.size(); i++) { sb.append(" + count"); sb.append(elements.get(i)); } sb.append(";\n"); } } sb.append(" return counts;\n}\n"); String javaSource = sb.toString(); //System.out.println("counter2 javaSource:\n" + javaSource); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classWriter.visit(Opcodes.V1_7, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC, COMPILED_COUNTER_CLASS2.replace('.', '/'), null, LONG_RANGE_COUNTER_TYPE.getInternalName(), null); classWriter.visitSource(javaSource, null); // Define "int countN" members: int numLeaves = elementaryIntervals.size(); for (int i = 0; i < numLeaves; i++) { classWriter.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_SYNTHETIC, "count" + i, "I", null, null); } // init: Method m = Method.getMethod("void <init> ()"); GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, m, null, null, classWriter); // Init all counters to 0: for (int i = 0; i < numLeaves; i++) { constructor.loadThis(); constructor.push(0); constructor.putField(COMPILED_COUNTER_CLASS2_TYPE, "count" + i, Type.INT_TYPE); } constructor.loadThis(); constructor.invokeConstructor(LONG_RANGE_COUNTER_TYPE, m); constructor.returnValue(); constructor.endMethod(); // void add(long v): GeneratorAdapter gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, ADD_METHOD, null, null, classWriter); buildCounterAsm2(gen, root, false); gen.returnValue(); gen.endMethod(); // int[] getCounts(): gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, GET_COUNTS_METHOD, null, null, classWriter); int countsLocal = gen.newLocal(INT_ARRAY_TYPE); gen.push(ranges.length); gen.newArray(Type.INT_TYPE); gen.storeLocal(countsLocal); for (int range = 0; range < ranges.length; range++) { List<Integer> elements = rangeToLeaf.get(range); if (elements != null) { gen.loadLocal(countsLocal); gen.push(range); gen.loadThis(); gen.getField(COMPILED_COUNTER_CLASS2_TYPE, "count" + elements.get(0), Type.INT_TYPE); for (int i = 1; i < elements.size(); i++) { gen.loadThis(); gen.getField(COMPILED_COUNTER_CLASS2_TYPE, "count" + elements.get(i), Type.INT_TYPE); gen.visitInsn(Opcodes.IADD); } gen.arrayStore(Type.INT_TYPE); } } gen.loadLocal(countsLocal); gen.returnValue(); gen.endMethod(); classWriter.visitEnd(); byte[] bytes = classWriter.toByteArray(); // javap -c /x/tmp/my.class /* try { FileOutputStream fos = new FileOutputStream(new File("/x/tmp/counter2.class")); fos.write(bytes); fos.close(); } catch (Exception e) { throw new RuntimeException(e); } */ // nocommit allow changing the class loader Class<? extends LongRangeCounter> cl = new CounterLoader(LongRangeCounter.class.getClassLoader()) .define(COMPILED_COUNTER_CLASS2, classWriter.toByteArray()); try { return cl.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new RuntimeException(e); } }
From source file:com.chiralbehaviors.janus.CompositeClassGenerator.java
License:Open Source License
protected void generateConstructor() { Type[] orderedMixIns = new Type[mixInTypes.length]; for (Map.Entry<Class<?>, Integer> entry : mixInTypeMapping.entrySet()) { orderedMixIns[entry.getValue()] = Type.getType(entry.getKey()); }//from w w w .j ava 2 s . c om Method constructor = new Method("<init>", Type.getMethodDescriptor(Type.VOID_TYPE, orderedMixIns)); GeneratorAdapter gen = new GeneratorAdapter(ACC_PUBLIC, constructor, null, new Type[] {}, writer); gen.visitCode(); gen.loadThis(); gen.invokeConstructor(Type.getType(Object.class), new Method("<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}))); for (int i = 0; i < orderedMixIns.length; i++) { gen.loadThis(); gen.loadArg(i); gen.putField(generatedType, MIX_IN_VAR_PREFIX + i, orderedMixIns[i]); } gen.returnValue(); gen.endMethod(); }
From source file:com.google.code.nanorm.internal.introspect.asm.AccessorBuilder.java
License:Apache License
/** * Generate code for getter constructor. * @param owner type representing the class being generated *//*w ww . j a v a 2s .c o m*/ private void visitConstructor(Type owner) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, ACCESSOR_CTOR, null, null, cw); mg.loadThis(); mg.invokeConstructor(OBJECT_TYPE, CTOR); mg.loadThis(); mg.loadArg(0); mg.putField(owner, "type", JL_REFLECT_TYPE_TYPE); mg.returnValue(); mg.endMethod(); }
From source file:com.google.code.nanorm.internal.introspect.asm.MapperBuilder.java
License:Apache License
/** * Generate constructor./* www . j ava 2 s. c om*/ * * @param cw class writer * @param owner self type * @param baseType */ private static void visitConstructor(ClassWriter cw, Type owner, Type baseType) { GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, MAPPER_CTOR, null, null, cw); mg.loadThis(); mg.invokeConstructor(baseType, CTOR); mg.loadThis(); mg.loadArg(0); mg.putField(owner, "delegate", QUERY_DELEGATE_TYPE); mg.loadThis(); mg.loadArg(1); mg.putField(owner, "configs", STATEMENT_CONFIGS_ARR_TYPE); mg.returnValue(); mg.endMethod(); }