Java Code Examples for org.objectweb.asm.MethodVisitor#visitLdcInsn()

The following examples show how to use org.objectweb.asm.MethodVisitor#visitLdcInsn() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeConstantAdjustmentTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testInstrumentationLegacyClassOtherType() throws Exception {
    ClassVisitor classVisitor = TypeConstantAdjustment.INSTANCE.wrap(mock(TypeDescription.class),
            this.classVisitor,
            mock(Implementation.Context.class),
            mock(TypePool.class),
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            IGNORED,
            IGNORED);
    classVisitor.visit(ClassFileVersion.JAVA_V4.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    MethodVisitor methodVisitor = classVisitor.visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    assertThat(methodVisitor, not(this.methodVisitor));
    methodVisitor.visitLdcInsn(FOO);
    verify(this.classVisitor).visit(ClassFileVersion.JAVA_V4.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verify(this.classVisitor).visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verifyNoMoreInteractions(this.classVisitor);
    verify(this.methodVisitor).visitLdcInsn(FOO);
    verifyNoMoreInteractions(this.methodVisitor);
}
 
Example 2
Source File: Globalizer.java    From Concurnas with MIT License 6 votes vote down vote up
private static void addstaticFinalVars(MethodVisitor mv, ArrayList<FieldVisitorHolder> staticFinalVars, String putTo) {
	for(FieldVisitorHolder sfv : staticFinalVars) {
		mv.visitLabel(new Label());
		mv.visitVarInsn(ALOAD, 0);
		
		switch(sfv.desc) {
			case "Ljava/lang/String;": mv.visitLdcInsn(sfv.value.toString()); break;
			case "J": BytecodeGenUtils.longOpcode(mv, ((Long)sfv.value).longValue() ); break;
			case "F": BytecodeGenUtils.floatOpcode(mv, ((Float)sfv.value).floatValue() ); break;
			case "D": BytecodeGenUtils.doubleOpcode(mv, ((Double)sfv.value).doubleValue() ); break;
			default: BytecodeGenUtils.intOpcode(mv, ((Integer)sfv.value).intValue() );
		}	
		
		mv.visitFieldInsn(PUTFIELD, putTo, sfv.name, sfv.desc);
	}
}
 
Example 3
Source File: AdviceGenerator.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void addCodeForSetTransactionX(MethodVisitor mv, String templateGetterName,
        String threadContextSetterName) {
    mv.visitVarInsn(ALOAD, 0);
    mv.visitVarInsn(ALOAD, 4);
    // methodMetaInternalName is non-null when transactionNameTemplate or
    // transactionUserTemplate are non-empty
    checkNotNull(methodMetaInternalName);
    mv.visitMethodInsn(INVOKEVIRTUAL, methodMetaInternalName, templateGetterName,
            "()Lorg/glowroot/agent/bytecode/api/MessageTemplate;", false);
    mv.visitVarInsn(ALOAD, 1);
    mv.visitVarInsn(ALOAD, 2);
    mv.visitVarInsn(ALOAD, 3);
    mv.visitMethodInsn(INVOKESTATIC, "org/glowroot/agent/bytecode/api/Bytecode",
            "getMessageText",
            "(Lorg/glowroot/agent/bytecode/api/MessageTemplate;Ljava/lang/Object;"
                    + "Ljava/lang/String;[Ljava/lang/Object;)"
                    + "Ljava/lang/String;",
            false);
    mv.visitLdcInsn(priorityForSetters);
    mv.visitMethodInsn(INVOKEINTERFACE, "org/glowroot/agent/plugin/api/ThreadContext",
            threadContextSetterName, "(Ljava/lang/String;I)V", true);
}
 
Example 4
Source File: TileEntityRegistry.java    From customstuff4 with GNU General Public License v3.0 6 votes vote down vote up
private static byte[] generateClass(Class<? extends TileEntity> baseClass, String className, String contentId)
{
    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, className, null, Type.getInternalName(baseClass), null);

    // Constructor
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitLdcInsn(contentId);
    mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(baseClass), "<init>", "(Ljava/lang/String;)V", false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(2, 1);
    mv.visitEnd();

    return cw.toByteArray();
}
 
Example 5
Source File: WriterHelper.java    From sumk with Apache License 2.0 6 votes vote down vote up
public static void visitInt(MethodVisitor mv, int num) {
	if (num == -1) {
		mv.visitInsn(ICONST_M1);
		return;
	}
	if (num >= 0 && num <= 5) {
		mv.visitInsn(ICONST_0 + num);
		return;
	}
	if (num <= Byte.MAX_VALUE && num >= Byte.MIN_VALUE) {
		mv.visitIntInsn(BIPUSH, num);
		return;
	}
	if (num <= Short.MAX_VALUE && num >= Short.MIN_VALUE) {
		mv.visitIntInsn(SIPUSH, num);
		return;
	}
	mv.visitLdcInsn(num);
}
 
Example 6
Source File: CodeEmitter.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
public void emitStringSwitch(Map<String, Label> labels, Label defaultCase, boolean caseInsensitive) {
    MethodVisitor mv = getMethodVisitor();
    if (caseInsensitive) {
        mv.visitFieldInsn(GETSTATIC, "java/util/Locale", "ENGLISH", "Ljava/util/Locale;");
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "toUpperCase", "(Ljava/util/Locale;)Ljava/lang/String;", false);
    }
    mv.visitInsn(DUP);
    AssignableValue tmp = allocate(String.class);
    tmp.write(BaseTypeAdapter.STRING).generate(this);
    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "hashCode", "()I", false);
    Multimap<Integer, SwitchLabel> keys = ArrayListMultimap.create();
    for (Map.Entry<String, Label> e : labels.entrySet()) {
        String name = e.getKey();
        if (caseInsensitive) {
            name = name.toUpperCase(Locale.ENGLISH);
        }
        keys.put(name.hashCode(), new SwitchLabel(name, e.getValue()));
    }
    List<Integer> codes = Lists.newArrayList(keys.keySet());
    Collections.sort(codes);
    int[] k = new int[codes.size()];
    Label[] kl = new Label[codes.size()];
    for (int i = 0; i < k.length; ++i) {
        k[i] = codes.get(i);
        kl[i] = new Label();
    }
    mv.visitLookupSwitchInsn(defaultCase, k, kl);
    for (int i = 0; i < k.length; ++i) {
        mv.visitLabel(kl[i]);
        for (SwitchLabel switchLabel : keys.get(k[i])) {
            mv.visitLdcInsn(switchLabel.name);
            tmp.read().generate(this);
            mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z", false);
            mv.visitJumpInsn(IFNE, switchLabel.label);
        }
        mv.visitJumpInsn(GOTO, defaultCase);
    }
}
 
Example 7
Source File: RegisterAutomaticSubscribers.java    From patchwork-patcher with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void accept(MethodVisitor method) {
	for (Map.Entry<String, EventBusSubscriber> entry : subscribers) {
		String baseName = entry.getKey();
		EventBusSubscriber subscriber = entry.getValue();

		// TODO: Check targetModId

		if (!subscriber.isClient() || !subscriber.isServer()) {
			if (System.getProperty("patchwork:ignore_sided_annotations", "false").equals("true")) {
				Patchwork.LOGGER.warn("Sided @EventBusSubscriber annotations are not supported yet, applying " + subscriber + " from " + baseName + " without sides.");
			} else {
				Patchwork.LOGGER.error("Sided @EventBusSubscriber annotations are not supported yet, skipping: " + subscriber + " attached to: " + baseName);
				continue;
			}
		}

		if (subscriber.getBus() == EventBusSubscriber.Bus.MOD) {
			method.visitMethodInsn(Opcodes.INVOKESTATIC, "net/minecraftforge/fml/javafmlmod/FMLJavaModLoadingContext", "get", "()Lnet/minecraftforge/fml/javafmlmod/FMLJavaModLoadingContext;", false);

			method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "net/minecraftforge/fml/javafmlmod/FMLJavaModLoadingContext", "getModEventBus", "()Lnet/minecraftforge/eventbus/api/IEventBus;", false);
		} else {
			method.visitFieldInsn(Opcodes.GETSTATIC, "net/minecraftforge/common/MinecraftForge", "EVENT_BUS", "Lnet/minecraftforge/eventbus/api/IEventBus;");
		}

		method.visitLdcInsn(Type.getObjectType(baseName));

		method.visitMethodInsn(Opcodes.INVOKEINTERFACE, "net/minecraftforge/eventbus/api/IEventBus", "register", "(Ljava/lang/Object;)V", true);
	}

	method.visitInsn(Opcodes.RETURN);

	method.visitMaxs(2, 0);
	method.visitEnd();
}
 
Example 8
Source File: BeansAccessBuilder.java    From json-smart-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * add Throws statement with int param 2
 */
private void throwExIntParam(MethodVisitor mv, Class<?> exCls) {
	String exSig = Type.getInternalName(exCls);
	mv.visitTypeInsn(NEW, exSig);
	mv.visitInsn(DUP);
	mv.visitLdcInsn("mapping " + this.className + " failed to map field:");
	mv.visitVarInsn(ILOAD, 2);
	mv.visitMethodInsn(INVOKESTATIC, "java/lang/Integer", "toString", "(I)Ljava/lang/String;");
	mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "concat", "(Ljava/lang/String;)Ljava/lang/String;");
	mv.visitMethodInsn(INVOKESPECIAL, exSig, "<init>", "(Ljava/lang/String;)V");
	mv.visitInsn(ATHROW);
}
 
Example 9
Source File: LdcTransformUnit.java    From authlib-agent with MIT License 5 votes vote down vote up
@Override
public ClassVisitor transform(ClassWriter writer) {
	return new LdcClassVisitor(writer) {

		@Override
		void checked(MethodVisitor mv) {
			mv.visitLdcInsn(replacement);
		}
	};
}
 
Example 10
Source File: ConstantExpr.java    From maple-ir with GNU General Public License v3.0 5 votes vote down vote up
private void packInt(MethodVisitor visitor, int value) {
	if (value >= -1 && value <= 5) {
		visitor.visitInsn(Opcodes.ICONST_M1 + (value + 1));
	} else if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) {
		visitor.visitIntInsn(Opcodes.BIPUSH, value);
	} else if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) {
		visitor.visitIntInsn(Opcodes.SIPUSH, value);
	} else {
		visitor.visitLdcInsn(value);
	}
}
 
Example 11
Source File: BytecodeHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Visits a class literal. If the type of the classnode is a primitive type,
 * the generated bytecode will be a GETSTATIC Integer.TYPE.
 * If the classnode is not a primitive type, we will generate a LDC instruction.
 */
public static void visitClassLiteral(MethodVisitor mv, ClassNode classNode) {
    if (ClassHelper.isPrimitiveType(classNode)) {
        mv.visitFieldInsn(
                GETSTATIC,
                getClassInternalName(ClassHelper.getWrapper(classNode)),
                "TYPE",
                "Ljava/lang/Class;");
    } else {
        mv.visitLdcInsn(org.objectweb.asm.Type.getType(getTypeDescription(classNode)));
    }
}
 
Example 12
Source File: VariableReference.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void generateCode(MethodVisitor mv, CodeFlow cf) {
	if (this.name.equals(ROOT)) {
		mv.visitVarInsn(ALOAD,1);
	}
	else {
		mv.visitVarInsn(ALOAD, 2);
		mv.visitLdcInsn(name);
		mv.visitMethodInsn(INVOKEINTERFACE, "org/springframework/expression/EvaluationContext", "lookupVariable", "(Ljava/lang/String;)Ljava/lang/Object;",true);
	}
	CodeFlow.insertCheckCast(mv,this.exitTypeDescriptor);
	cf.pushDescriptor(this.exitTypeDescriptor);
}
 
Example 13
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitVariableExpression(final VariableExpression expression) {
    final String variableName = expression.getName();

    if (expression.isThisExpression()) {
        // "this" in static context is Class instance
        if (controller.isStaticMethod() || controller.getCompileStack().isInSpecialConstructorCall()
                || (!controller.getCompileStack().isImplicitThis() && controller.isStaticContext())) {
            ClassNode thisType = controller.getClassNode();
            if (controller.isInGeneratedFunction()) {
                do { thisType = thisType.getOuterClass();
                } while (ClassHelper.isGeneratedFunction(thisType));
            }
            classX(thisType).visit(this);
        } else {
            loadThis(expression);
        }
        return;
    }

    if (expression.isSuperExpression()) {
        // "super" in static context is Class instance
        if (controller.isStaticMethod()) {
            ClassNode superType = controller.getClassNode().getSuperClass();
            classX(superType).visit(this);
        } else {
            loadThis(expression);
        }
        return;
    }

    BytecodeVariable variable = controller.getCompileStack().getVariable(variableName, false);
    if (variable != null) {
        controller.getOperandStack().loadOrStoreVariable(variable, expression.isUseReferenceDirectly());
    } else if (passingParams && controller.isInScriptBody()) {
        MethodVisitor mv = controller.getMethodVisitor();
        mv.visitTypeInsn(NEW, "org/codehaus/groovy/runtime/ScriptReference");
        mv.visitInsn(DUP);
        loadThisOrOwner();
        mv.visitLdcInsn(variableName);
        mv.visitMethodInsn(INVOKESPECIAL, "org/codehaus/groovy/runtime/ScriptReference", "<init>", "(Lgroovy/lang/Script;Ljava/lang/String;)V", false);
    } else {
        PropertyExpression pexp = thisPropX(true, variableName);
        pexp.getObjectExpression().setSourcePosition(expression);
        pexp.getProperty().setSourcePosition(expression);
        pexp.visit(this);
    }

    if (!controller.getCompileStack().isLHS()) {
        controller.getAssertionWriter().record(expression);
    }
}
 
Example 14
Source File: IntegerConstant.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    methodVisitor.visitLdcInsn(value);
    return SIZE;
}
 
Example 15
Source File: ReactivePanacheMongoEntityEnhancer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
protected void injectModel(MethodVisitor mv) {
    mv.visitLdcInsn(thisClass);
}
 
Example 16
Source File: PushLongConst.java    From turin-programming-language with Apache License 2.0 4 votes vote down vote up
@Override
public void operate(MethodVisitor mv) {
    mv.visitLdcInsn(value);
}
 
Example 17
Source File: ProxyChannelFactory.java    From JCTools with Apache License 2.0 4 votes vote down vote up
private static void implementConstructor(ClassVisitor classVisitor,
        Class<? extends ProxyChannelRingBuffer> parentType,
        String generatedName,
        int primitiveMessageSize,
        int referenceMessageSize) {
    MethodVisitor methodVisitor = classVisitor.visitMethod(Opcodes.ACC_PUBLIC,
            "<init>",
            methodDescriptor(void.class,
                    int.class,
                    WaitStrategy.class),
            null,
            null);
    methodVisitor.visitCode();
    
    LocalsHelper locals = LocalsHelper.forInstanceMethod();
    int localIndexOfCapacity = locals.newLocal(int.class);
    int localIndexOfWaitStrategy = locals.newLocal(WaitStrategy.class);

    methodVisitor.visitVarInsn(Opcodes.ALOAD, LOCALS_INDEX_THIS);
    methodVisitor.visitVarInsn(Opcodes.ILOAD, localIndexOfCapacity);
    methodVisitor.visitLdcInsn(primitiveMessageSize);
    methodVisitor.visitLdcInsn(referenceMessageSize);
    
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL,
            Type.getInternalName(parentType),
            "<init>",
            methodDescriptor(void.class,
                    int.class,
                    int.class,
                    int.class),
            false);
    
    methodVisitor.visitVarInsn(Opcodes.ALOAD, LOCALS_INDEX_THIS);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, localIndexOfWaitStrategy);
    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedName, "waitStrategy", Type.getDescriptor(WaitStrategy.class));
    
    methodVisitor.visitInsn(Opcodes.RETURN);

    methodVisitor.visitMaxs(-1, -1);
    methodVisitor.visitEnd();
}
 
Example 18
Source File: TestEnumForJavacDump.java    From AVM with MIT License 4 votes vote down vote up
public static byte[] generateBytecode() {
    ClassWriter classWriter = new ClassWriter(0);
    FieldVisitor fieldVisitor;
    MethodVisitor methodVisitor;

    classWriter.visit(V10, ACC_PUBLIC | ACC_FINAL | ACC_SUPER | ACC_ENUM, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "Ljava/lang/Enum<L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;>;", "java/lang/Enum", null);

    {
        fieldVisitor = classWriter.visitField(ACC_PUBLIC | ACC_FINAL | ACC_STATIC | ACC_ENUM, "TEST", "L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", null, null);
        fieldVisitor.visitEnd();
    }
    {
        fieldVisitor = classWriter.visitField(ACC_PRIVATE | ACC_FINAL | ACC_STATIC | ACC_SYNTHETIC, "$VALUES", "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", null, null);
        fieldVisitor.visitEnd();
    }
    {
        methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_STATIC, "values", "()[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitFieldInsn(GETSTATIC, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "$VALUES", "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitMethodInsn(INVOKEVIRTUAL, "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", "clone", "()Ljava/lang/Object;", false);
        methodVisitor.visitTypeInsn(CHECKCAST, "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(ARETURN);
        methodVisitor.visitMaxs(1, 0);
        methodVisitor.visitEnd();
    }
    {
        methodVisitor = classWriter.visitMethod(ACC_PUBLIC | ACC_STATIC, "valueOf", "(Ljava/lang/String;)L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitLdcInsn(Type.getType("L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;"));
        methodVisitor.visitVarInsn(ALOAD, 0);
        methodVisitor.visitMethodInsn(INVOKESTATIC, "java/lang/Enum", "valueOf", "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;", false);
        methodVisitor.visitTypeInsn(CHECKCAST, PACKAGE_NAME_INTERNAL + "/TestEnumForValues");
        methodVisitor.visitInsn(ARETURN);
        methodVisitor.visitMaxs(2, 1);
        methodVisitor.visitEnd();
    }
    {
        methodVisitor = classWriter.visitMethod(ACC_PRIVATE, "<init>", "(Ljava/lang/String;I)V", "()V", null);
        methodVisitor.visitCode();
        methodVisitor.visitVarInsn(ALOAD, 0);
        methodVisitor.visitVarInsn(ALOAD, 1);
        methodVisitor.visitVarInsn(ILOAD, 2);
        methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Enum", "<init>", "(Ljava/lang/String;I)V", false);
        methodVisitor.visitInsn(RETURN);
        methodVisitor.visitMaxs(3, 3);
        methodVisitor.visitEnd();
    }
    {
        methodVisitor = classWriter.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitTypeInsn(NEW, PACKAGE_NAME_INTERNAL + "/TestEnumForValues");
        methodVisitor.visitInsn(DUP);
        methodVisitor.visitLdcInsn("TEST");
        methodVisitor.visitInsn(ICONST_0);
        methodVisitor.visitMethodInsn(INVOKESPECIAL, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "<init>", "(Ljava/lang/String;I)V", false);
        methodVisitor.visitFieldInsn(PUTSTATIC, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "TEST", "L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(ICONST_1);
        methodVisitor.visitTypeInsn(ANEWARRAY, PACKAGE_NAME_INTERNAL + "/TestEnumForValues");
        methodVisitor.visitInsn(DUP);
        methodVisitor.visitInsn(ICONST_0);
        methodVisitor.visitFieldInsn(GETSTATIC, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "TEST", "L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(AASTORE);
        methodVisitor.visitFieldInsn(PUTSTATIC, PACKAGE_NAME_INTERNAL + "/TestEnumForValues", "$VALUES", "[L" + PACKAGE_NAME_INTERNAL + "/TestEnumForValues;");
        methodVisitor.visitInsn(RETURN);
        methodVisitor.visitMaxs(4, 0);
        methodVisitor.visitEnd();
    }
    classWriter.visitEnd();

    return classWriter.toByteArray();
}
 
Example 19
Source File: AsmTest.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws Throwable {

    ClassReader cr = new ClassReader(Config.class.getName());
    ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
    ClassVisitor cv = new MethodChangeClassAdapter(cw);
    cr.accept(cv, Opcodes.ASM5);

    //Add a new method
    MethodVisitor mw = cw.visitMethod(ACC_PUBLIC + ACC_STATIC,
                                      "add",
                                      "([Ljava/lang/String;)V",
                                      null,
                                      null);

    // pushes the 'out' field (of type PrintStream) of the System class
    mw.visitFieldInsn(GETSTATIC,
                      "java/lang/System",
                      "out",
                      "Ljava/io/PrintStream;");
    // pushes the "Hello World!" String constant
    mw.visitLdcInsn("this is add method print!");
    // invokes the 'println' method (defined in the PrintStream class)
    mw.visitMethodInsn(INVOKEVIRTUAL,
                       "java/io/PrintStream",
                       "println",
                       "(Ljava/lang/String;)V");
    mw.visitInsn(RETURN);
    // this code uses a maximum of two stack elements and two local
    // variables
    mw.visitMaxs(0, 0);
    mw.visitEnd();


    //Type.getDescriptor(AdviceFlowOuterHolder.class)
    FieldVisitor fv = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL,
                                     "age",
                                    Type.INT_TYPE.toString(),
                                     null,
                                     1);
    fv.visitEnd();

    FieldVisitor fv2 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL,
                                    "name2",
                                    Type.getDescriptor(String.class),
                                    null,
                                    "name2");
    fv2.visitEnd();


    ModifyClassVisiter cv2 = new ModifyClassVisiter(Opcodes.ASM5);
    cv2.addRemoveField("name");
    cr.accept(cv2, Opcodes.ASM5);

    FieldVisitor fv3 = cw.visitField(ACC_PUBLIC + ACC_STATIC + ACC_FINAL,
                                     "name",
                                     Type.getDescriptor(String.class),
                                     null,
                                     "name");
    fv3.visitEnd();




    byte[] code = cw.toByteArray();
    File file = new File("Config.class");
    System.out.println(file.getAbsolutePath());
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(code);
    fos.close();

}
 
Example 20
Source File: ASMConstants.java    From The-5zig-Mod with MIT License 4 votes vote down vote up
public static void addSystemOut(MethodVisitor mv, String message) {
	mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
	mv.visitLdcInsn(message);
	mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
}