org.objectweb.asm.MethodVisitor Java Examples

The following examples show how to use org.objectweb.asm.MethodVisitor. 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: PatchGuiIngameForge.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
	if (Names.renderGameOverlayForge.equals(name, desc)) {
		LogUtil.startMethod(Names.renderGameOverlayForge.getName() + " " + Names.renderGameOverlayForge.getDesc());
		return new PatchRenderGameOverlay(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	if (Names.ingameTick.equals(name, desc)) {
		LogUtil.startMethod(Names.ingameTick.getName() + " " + Names.ingameTick.getDesc());
		return new PatchTick(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	if (Names.renderChatForge.equals(name, desc)) {
		LogUtil.startMethod(Names.renderChatForge.getName() + " " + Names.renderChatForge.getDesc());
		return new PatchChat(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	LogUtil.endMethod();
	return super.visitMethod(access, name, desc, signature, exceptions);
}
 
Example #2
Source File: Concurnifier.java    From Concurnas with MIT License 6 votes vote down vote up
public static void boxIfPrimative(MethodVisitor mv, String desc) {
	if( desc.startsWith("L") || desc.startsWith("[")){//object or array - do nothing
		return;
	}
	else{
		switch(desc){
			case "Z": mv.visitFieldInsn(INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;"); break;
			case "B": mv.visitFieldInsn(INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;"); break;
			case "C": mv.visitFieldInsn(INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;"); break;
			case "S": mv.visitFieldInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(S)Ljava/lang/Integer;"); break;//TODO: short is wrong who cares
			case "I": mv.visitFieldInsn(INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;"); break;
			case "J": mv.visitFieldInsn(INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;"); break;
			case "F": mv.visitFieldInsn(INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;"); break;
			case "D": mv.visitFieldInsn(INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;"); break;
		}
	}		
}
 
Example #3
Source File: IndyCompile.java    From cs-summary-reflection with Apache License 2.0 6 votes vote down vote up
@Override
void compile(final MethodVisitor mv) {
    // compiles e1
    e1.compile(mv);
    // tests if e1 is true
    mv.visitInsn(DUP);
    // convert to a boolean
    mv.visitInvokeDynamicInsn("asBoolean", "(Ljava/lang/Object;)Z", UNARY);
    Label end = new Label();
    mv.visitJumpInsn(IFNE, end);
    // case where e1 is false : e1 || e2 is equal to e2
    mv.visitInsn(POP);
    e2.compile(mv);
    // if e1 is true, e1 || e2 is equal to e1:
    // we jump directly to this label, without evaluating e2
    mv.visitLabel(end);
}
 
Example #4
Source File: StatementWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void writeCaseStatement(final CaseStatement statement, final int switchVariableIndex, final Label thisLabel, final Label nextLabel) {
    controller.getAcg().onLineNumber(statement, "visitCaseStatement");
    MethodVisitor mv = controller.getMethodVisitor();
    OperandStack operandStack = controller.getOperandStack();

    mv.visitVarInsn(ALOAD, switchVariableIndex);

    statement.getExpression().visit(controller.getAcg());
    operandStack.box();
    controller.getBinaryExpressionHelper().getIsCaseMethod().call(mv);
    operandStack.replace(ClassHelper.boolean_TYPE);

    Label l0 = controller.getOperandStack().jump(IFEQ);

    mv.visitLabel(thisLabel);

    statement.getCode().visit(controller.getAcg());

    // now if we don't finish with a break we need to jump past the next comparison
    if (nextLabel != null) {
        mv.visitJumpInsn(GOTO, nextLabel);
    }

    mv.visitLabel(l0);
}
 
Example #5
Source File: ClassConstantsCollector.java    From JByteMod-Beta with GNU General Public License v2.0 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
  if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
    cp.newUTF8("Synthetic");
  }
  if ((access & Opcodes.ACC_DEPRECATED) != 0) {
    cp.newUTF8("Deprecated");
  }
  cp.newUTF8(name);
  cp.newUTF8(desc);
  if (signature != null) {
    cp.newUTF8("Signature");
    cp.newUTF8(signature);
  }
  if (exceptions != null) {
    cp.newUTF8("Exceptions");
    for (int i = 0; i < exceptions.length; ++i) {
      cp.newClass(exceptions[i]);
    }
  }
  return new MethodConstantsCollector(cv.visitMethod(access, name, desc, signature, exceptions), cp);
}
 
Example #6
Source File: Compile.java    From cs-summary-reflection with Apache License 2.0 6 votes vote down vote up
@Override
void compile(final MethodVisitor mv) {
    // 编译e1
    e1.compile(mv);
    // 判断测试,e1是否为false
    mv.visitInsn(DUP);
    Label end = new Label();
    mv.visitJumpInsn(IFEQ, end);
    // e1为true的情况: e1 && e2 is equal to e2
    mv.visitInsn(POP);
    e2.compile(mv);
    // e1为假的情况: e1 && e2 is equal to e1:
    // 我们直接跳到这个标签,而不计算e2
    // e2是否需要计算取决于e1
    mv.visitLabel(end);
}
 
Example #7
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testExplicitTypeInitializer() throws Exception {
    assertThat(createPlain()
            .defineField(FOO, String.class, Ownership.STATIC, Visibility.PUBLIC)
            .initializer(new ByteCodeAppender() {
                public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
                    return new Size(new StackManipulation.Compound(
                            new TextConstant(FOO),
                            FieldAccess.forField(instrumentedMethod.getDeclaringType().getDeclaredFields().filter(named(FOO)).getOnly()).write()
                    ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
                }
            }).make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredField(FOO)
            .get(null), is((Object) FOO));
}
 
Example #8
Source File: ConstructorAdapter.java    From yql-plus with Apache License 2.0 6 votes vote down vote up
@Override
public void invokeSpecial(final Class<?> clazz, final List<BytecodeExpression> arguments) {
    final Type[] args = new Type[arguments.size()];
    for (int i = 0; i < arguments.size(); ++i) {
        args[i] = arguments.get(i).getType().getJVMType();
    }
    unit.setSuperInit(
            new BytecodeSequence() {
                @Override
                public void generate(CodeEmitter code) {
                    code.exec(code.getLocal("this"));
                    for (BytecodeExpression e : arguments) {
                        code.exec(e);
                    }
                    MethodVisitor mv = code.getMethodVisitor();
                    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(clazz), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, args), false);
                }
            }
    );
}
 
Example #9
Source File: PatchGuiIngameForge.java    From The-5zig-Mod with MIT License 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
	if (Names.renderGameOverlayForge.equals(name, desc)) {
		LogUtil.startMethod(Names.renderGameOverlayForge.getName() + " " + Names.renderGameOverlayForge.getDesc());
		return new PatchRenderGameOverlay(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	if (Names.ingameTick.equals(name, desc)) {
		LogUtil.startMethod(Names.ingameTick.getName() + " " + Names.ingameTick.getDesc());
		return new PatchTick(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	if (Names.renderChatForge.equals(name, desc)) {
		LogUtil.startMethod(Names.renderChatForge.getName() + " " + Names.renderChatForge.getDesc());
		return new PatchChat(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	LogUtil.endMethod();
	return super.visitMethod(access, name, desc, signature, exceptions);
}
 
Example #10
Source File: PeripheralCodeGenerator.java    From OpenPeripheral with MIT License 6 votes vote down vote up
private static void createConstructor(ClassWriter writer, String clsName, Type targetType, Type baseType) {
	final Type ctorType = Type.getMethodType(Type.VOID_TYPE, targetType);

	MethodVisitor init = writer.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, "<init>", ctorType.getDescriptor(), null, null);
	init.visitCode();
	init.visitVarInsn(Opcodes.ALOAD, 0);
	init.visitVarInsn(Opcodes.ALOAD, 1);
	init.visitInsn(Opcodes.DUP2);
	init.visitMethodInsn(Opcodes.INVOKESPECIAL, baseType.getInternalName(), "<init>", SUPER_CTOR_TYPE.getDescriptor(), false);
	init.visitFieldInsn(Opcodes.PUTFIELD, clsName, CommonMethodsBuilder.TARGET_FIELD_NAME, targetType.getDescriptor());
	init.visitInsn(Opcodes.RETURN);

	init.visitMaxs(0, 0);

	init.visitEnd();
}
 
Example #11
Source File: IfTests.java    From Despector with MIT License 6 votes vote down vote up
@Test
public void testOr() {
    TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V");
    MethodVisitor mv = builder.getGenerator();
    Label start = new Label();
    mv.visitLabel(start);
    Label ret = new Label();
    Label body = new Label();
    mv.visitVarInsn(ILOAD, 0);
    mv.visitJumpInsn(IFNE, body);
    mv.visitVarInsn(ILOAD, 1);
    mv.visitJumpInsn(IFEQ, ret);
    mv.visitLabel(body);
    mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false);
    mv.visitLabel(ret);
    mv.visitInsn(RETURN);
    mv.visitLocalVariable("a", "Z", null, start, ret, 0);
    mv.visitLocalVariable("b", "Z", null, start, ret, 1);

    String insn = TestHelper.getAsString(builder.finish(), "test_mth");
    String good = "if (a || b) {\n"
            + "    org.spongepowered.test.decompile.IfTests.body();\n"
            + "}";
    Assert.assertEquals(good, insn);
}
 
Example #12
Source File: WhileTests.java    From Despector with MIT License 6 votes vote down vote up
@Test
public void testWhileInverse() {
    TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(I)V");
    MethodVisitor mv = builder.getGenerator();
    Label start = new Label();
    mv.visitLabel(start);
    Label end = new Label();
    Label l1 = new Label();
    Label l2 = new Label();
    mv.visitJumpInsn(GOTO, l2);
    mv.visitLabel(l1);
    mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false);
    mv.visitLabel(l2);
    mv.visitVarInsn(ILOAD, 0);
    mv.visitInsn(ICONST_5);
    mv.visitJumpInsn(IF_ICMPLT, l1);
    mv.visitLabel(end);
    mv.visitInsn(RETURN);
    mv.visitLocalVariable("i", "I", null, start, end, 0);

    String insn = TestHelper.getAsString(builder.finish(), "test_mth");
    String good = "while (i < 5) {\n"
            + "    org.spongepowered.test.decompile.WhileTests.body();\n"
            + "}";
    Assert.assertEquals(good, insn);
}
 
Example #13
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void loadThis(final VariableExpression thisOrSuper) {
    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitVarInsn(ALOAD, 0);
    if (controller.isInGeneratedFunction() && !controller.getCompileStack().isImplicitThis()) {
        mv.visitMethodInsn(INVOKEVIRTUAL, "groovy/lang/Closure", "getThisObject", "()Ljava/lang/Object;", false);
        ClassNode expectedType = controller.getTypeChooser().resolveType(thisOrSuper, controller.getOutermostClass());
        if (!ClassHelper.OBJECT_TYPE.equals(expectedType) && !ClassHelper.isPrimitiveType(expectedType)) {
            BytecodeHelper.doCast(mv, expectedType);
            controller.getOperandStack().push(expectedType);
        } else {
            controller.getOperandStack().push(ClassHelper.OBJECT_TYPE);
        }
    } else {
        controller.getOperandStack().push(controller.getClassNode());
    }
}
 
Example #14
Source File: CreateTest.java    From AVM with MIT License 6 votes vote down vote up
private byte[] getByteCodeForClassWithoutSuperName() {
    ClassWriter classWriter = new ClassWriter(0);
    MethodVisitor methodVisitor;

    classWriter.visit(V10, ACC_PUBLIC | ACC_SUPER, "b/Main", null, null, null);

    classWriter.visitSource("Main.java", null);
    {
        methodVisitor = classWriter.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        methodVisitor.visitCode();
        Label label0 = new Label();
        methodVisitor.visitLabel(label0);
        methodVisitor.visitLineNumber(3, label0);
        methodVisitor.visitVarInsn(ALOAD, 0);
        methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        methodVisitor.visitInsn(RETURN);
        methodVisitor.visitMaxs(1, 1);
        methodVisitor.visitEnd();
    }
    classWriter.visitEnd();

    return classWriter.toByteArray();
}
 
Example #15
Source File: StaticInitMerger.java    From Concurnas with MIT License 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(
    final int access,
    final String name,
    final String descriptor,
    final String signature,
    final String[] exceptions) {
  MethodVisitor methodVisitor;
  if ("<clinit>".equals(name)) {
    int newAccess = Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC;
    String newName = renamedClinitMethodPrefix + numClinitMethods++;
    methodVisitor = super.visitMethod(newAccess, newName, descriptor, signature, exceptions);

    if (mergedClinitVisitor == null) {
      mergedClinitVisitor = super.visitMethod(newAccess, name, descriptor, null, null);
    }
    mergedClinitVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, owner, newName, descriptor, false);
  } else {
    methodVisitor = super.visitMethod(access, name, descriptor, signature, exceptions);
  }
  return methodVisitor;
}
 
Example #16
Source File: MethodConstant.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    TypeDescription auxiliaryType = implementationContext.register(PrivilegedMemberLookupAction.of(methodDescription));
    return new Compound(
            TypeCreation.of(auxiliaryType),
            Duplication.SINGLE,
            ClassConstant.of(methodDescription.getDeclaringType()),
            methodName,
            ArrayFactory.forType(TypeDescription.Generic.OfNonGenericType.CLASS)
                    .withValues(typeConstantsFor(methodDescription.getParameters().asTypeList().asErasures())),
            MethodInvocation.invoke(auxiliaryType.getDeclaredMethods().filter(isConstructor()).getOnly()),
            MethodInvocation.invoke(DO_PRIVILEGED),
            TypeCasting.to(TypeDescription.ForLoadedType.of(methodDescription.isConstructor()
                    ? Constructor.class
                    : Method.class))
    ).apply(methodVisitor, implementationContext);
}
 
Example #17
Source File: LocalVariableAnnotationNode.java    From Concurnas with MIT License 5 votes vote down vote up
/**
 * Makes the given visitor visit this type annotation.
 *
 * @param methodVisitor the visitor that must visit this annotation.
 * @param visible {@literal true} if the annotation is visible at runtime.
 */
public void accept(final MethodVisitor methodVisitor, final boolean visible) {
  Label[] startLabels = new Label[this.start.size()];
  Label[] endLabels = new Label[this.end.size()];
  int[] indices = new int[this.index.size()];
  for (int i = 0, n = startLabels.length; i < n; ++i) {
    startLabels[i] = this.start.get(i).getLabel();
    endLabels[i] = this.end.get(i).getLabel();
    indices[i] = this.index.get(i);
  }
  accept(
      methodVisitor.visitLocalVariableAnnotation(
          typeRef, typePath, startLabels, endLabels, indices, desc, visible));
}
 
Example #18
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void onLineNumber(final ASTNode statement, final String message) {
    if (statement == null || statement instanceof BlockStatement) return;

    currentASTNode = statement;
    int line = statement.getLineNumber();
    if (line < 0 || (!ASM_DEBUG && line == controller.getLineNumber())) return;

    controller.setLineNumber(line);
    MethodVisitor mv = controller.getMethodVisitor();
    if (mv != null) {
        Label l = new Label();
        mv.visitLabel(l);
        mv.visitLineNumber(line, l);
    }
}
 
Example #19
Source File: AdviceDeadCodeTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);
    methodVisitor.visitInsn(Opcodes.ARETURN);
    methodVisitor.visitInsn(Opcodes.POP); // dead code
    methodVisitor.visitInsn(Opcodes.ACONST_NULL);
    methodVisitor.visitInsn(Opcodes.ARETURN);
    return new Size(1, instrumentedMethod.getStackSize());
}
 
Example #20
Source File: CodeEmitter.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
public void emitIntegerSwitch(Map<Integer, Label> labels, Label defaultCase) {
    // TODO: we should see if the labels are dense, and if so use TABLESWITCH
    MethodVisitor mv = getMethodVisitor();
    List<Integer> codes = Lists.newArrayList(labels.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] = labels.get(i);
    }
    mv.visitLookupSwitchInsn(defaultCase, k, kl);
    mv.visitJumpInsn(GOTO, defaultCase);
}
 
Example #21
Source File: CommonMethodsBuilder.java    From OpenPeripheral with MIT License 5 votes vote down vote up
private static void visitIntConst(MethodVisitor mv, int value) {
	switch (value) {
		case 0:
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
			mv.visitInsn(Opcodes.ICONST_0 + value);
			break;
		default:
			mv.visitLdcInsn(value);
			break;
	}
}
 
Example #22
Source File: ArraysRequiringAnalysisMethodNode.java    From AVM with MIT License 5 votes vote down vote up
public ArraysRequiringAnalysisMethodNode(final int access,
                                     final String name,
                                     final String descriptor,
                                     final String signature,
                                     final String[] exceptions,
                                     MethodVisitor mv,
                                     String className,
                                     ClassHierarchy hierarchy)
{
    super(Opcodes.ASM6, access, name, descriptor, signature, exceptions);
    this.className = className;
    this.mv = mv;
    this.hierarchy = hierarchy;
}
 
Example #23
Source File: PatchGuiConnecting.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
	if (Names.guiConnectingInit1.equals(name, desc)) {
		LogUtil.startMethod(Names.guiConnectingInit1.getName() + " " + Names.guiConnectingInit1.getDesc());
		return new PatchInitGui1(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	if (Names.guiConnectingInit2.equals(name, desc)) {
		LogUtil.startMethod(Names.guiConnectingInit2.getName() + " " + Names.guiConnectingInit2.getDesc());
		return new PatchInitGui2(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	LogUtil.endMethod();
	return super.visitMethod(access, name, desc, signature, exceptions);
}
 
Example #24
Source File: OBBN3Mutator.java    From pitest with Apache License 2.0 5 votes vote down vote up
OBBNMethodVisitor3(final MethodMutatorFactory factory,
                   final MutationContext context, final MethodInfo info, final MethodVisitor delegateMethodVisitor)  {
    super(ASMVersion.ASM_VERSION, info.getAccess(), info.getMethodDescriptor(), delegateMethodVisitor);
    this.factory = factory;
    this.context = context;
    this.info = info;
}
 
Example #25
Source File: PatchGuiEditSign.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
	if (Names.guiClosed.equals(name, desc)) {
		LogUtil.startMethod(Names.guiClosed.getName() + " " + Names.guiClosed.getDesc());
		return new PatchGuiClosed(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	LogUtil.endMethod();
	return super.visitMethod(access, name, desc, signature, exceptions);
}
 
Example #26
Source File: LDCConstant.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Override
public void generate(CodeEmitter environment) {
    MethodVisitor mv = environment.getMethodVisitor();
    if (constant instanceof Integer) {
        environment.emitIntConstant((int) constant);
    } else {
        mv.visitLdcInsn(constant);
    }
}
 
Example #27
Source File: InterfaceDesugaring.java    From bazel with Apache License 2.0 5 votes vote down vote up
public InterfaceInvocationRewriter(
    MethodVisitor dest,
    @Nullable String knownInterfaceName,
    ClassReaderFactory bootclasspath,
    ClassLoader targetLoader,
    DependencyCollector depsCollector,
    String declaringClass) {
  super(Opcodes.ASM8, dest);
  this.interfaceName = knownInterfaceName;
  this.bootclasspath = bootclasspath;
  this.targetLoader = targetLoader;
  this.depsCollector = depsCollector;
  this.declaringClass = declaringClass;
}
 
Example #28
Source File: PatchEntityPlayerSP.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
	if (Names.sendChatMessage.equals(name, desc)) {
		LogUtil.startMethod(Names.sendChatMessage.getName() + " " + Names.sendChatMessage.getDesc());
		return new PatchSendChatMessage(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	LogUtil.endMethod();
	return super.visitMethod(access, name, desc, signature, exceptions);
}
 
Example #29
Source File: DecoratingDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDecorationWithoutAnnotationRetention() throws Exception {
    Object instance = new ByteBuddy()
            .with(AnnotationRetention.DISABLED)
            .decorate(Foo.class)
            .annotateType(AnnotationDescription.Builder.ofType(Qux.class).build())
            .ignoreAlso(new LatentMatcher.Resolved<MethodDescription>(none()))
            .visit(new AsmVisitorWrapper.ForDeclaredMethods()
                    .method(named(FOO), new AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper() {
                        public MethodVisitor wrap(TypeDescription instrumentedType,
                                                  MethodDescription instrumentedMethod,
                                                  MethodVisitor methodVisitor,
                                                  Implementation.Context implementationContext,
                                                  TypePool typePool,
                                                  int writerFlags,
                                                  int readerFlags) {
                            return new MethodVisitor(OpenedClassReader.ASM_API, methodVisitor) {
                                @Override
                                public void visitLdcInsn(Object value) {
                                    if (FOO.equals(value)) {
                                        value = BAR;
                                    }
                                    super.visitLdcInsn(value);
                                }
                            };
                        }
                    }))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getConstructor()
            .newInstance();
    assertThat(instance.getClass().getMethod(FOO).invoke(instance), is((Object) BAR));
    assertThat(instance.getClass().isAnnotationPresent(Bar.class), is(true));
    assertThat(instance.getClass().isAnnotationPresent(Qux.class), is(true));
}
 
Example #30
Source File: PatchGuiOptions.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
	if (Names.initGui.equals(name, desc)) {
		LogUtil.startMethod("InitGui " + Names.initGui.getName() + "(%s)", Names.initGui.getDesc());
		return new PatchInitGui(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	if (Names.actionPerformed.equals(name, desc)) {
		LogUtil.startMethod("actionPerformed " + Names.actionPerformed.getName() + "(%s)", Names.actionPerformed.getDesc());
		return new PatchActionPerformed(cv.visitMethod(access, name, desc, signature, exceptions));
	}
	LogUtil.endMethod();
	return super.visitMethod(access, name, desc, signature, exceptions);
}