当前位置: 首页>>代码示例>>Java>>正文


Java MethodVisitor.visitFieldInsn方法代码示例

本文整理汇总了Java中org.objectweb.asm.MethodVisitor.visitFieldInsn方法的典型用法代码示例。如果您正苦于以下问题:Java MethodVisitor.visitFieldInsn方法的具体用法?Java MethodVisitor.visitFieldInsn怎么用?Java MethodVisitor.visitFieldInsn使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.objectweb.asm.MethodVisitor的用法示例。


在下文中一共展示了MethodVisitor.visitFieldInsn方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: generateMethodTest10

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
/**
 *  Generate test with an invokedynamic, a static bootstrap method with an extra arg that is a
 *  MethodHandle of kind get static. The method handle read a static field from a class.
 */
private void generateMethodTest10(ClassVisitor cv) {
  MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "test10", "()V",
      null, null);
  MethodType mt = MethodType.methodType(CallSite.class, MethodHandles.Lookup.class, String.class,
      MethodType.class, MethodHandle.class);
  Handle bootstrap = new Handle(Opcodes.H_INVOKESTATIC, Type.getInternalName(InvokeCustom.class),
      "bsmCreateCallCallingtargetMethod", mt.toMethodDescriptorString(), false);
  mv.visitFieldInsn(Opcodes.GETSTATIC,
      "java/lang/System",
      "out",
      "Ljava/io/PrintStream;");
  mv.visitInvokeDynamicInsn("staticField1", "()Ljava/lang/String;", bootstrap,
      new Handle(Opcodes.H_GETSTATIC, Type.getInternalName(InvokeCustom.class),
          "staticField1", "Ljava/lang/String;", false));
  mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
      "java/io/PrintStream",
      "println",
      "(Ljava/lang/String;)V", false);
  mv.visitInsn(Opcodes.RETURN);
  mv.visitMaxs(-1, -1);
}
 
开发者ID:inferjay,项目名称:r8,代码行数:26,代码来源:TestGenerator.java

示例2: generateParametersGetter

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
private static void generateParametersGetter(ClassWriter cw, String selfClassInternalName, String selfClassDescriptor) {
    MethodVisitor mv;
    mv = cw.visitMethod(ACC_PUBLIC, "parameters", "()Ljava/util/List;", "()Ljava/util/List<Ljava/lang/reflect/Parameter;>;", null);
    mv.visitCode();
    Label l0 = new Label();
    mv.visitLabel(l0);
    mv.visitVarInsn(ALOAD, 0);
    mv.visitFieldInsn(GETFIELD, selfClassInternalName, "parameters", "Ljava/util/List;");
    mv.visitInsn(ARETURN);
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLocalVariable("this", selfClassDescriptor, null, l0, l1, 0);
    mv.visitMaxs(-1, -1);
    mv.visitEnd();
}
 
开发者ID:primeval-io,项目名称:primeval-reflex,代码行数:16,代码来源:MethodArgumentsGenerator.java

示例3: applyConventionMappingToSetter

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
public void applyConventionMappingToSetter(PropertyMetaData property, Method setter) throws Exception {
    // GENERATE public <return-type> <setter>(<type> v) { <return-type> v = super.<setter>(v); __<prop>__ = true; return v; }

    Type paramType = Type.getType(setter.getParameterTypes()[0]);
    Type returnType = Type.getType(setter.getReturnType());
    String setterDescriptor = Type.getMethodDescriptor(returnType, paramType);
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, setter.getName(), setterDescriptor, null, EMPTY_STRINGS);
    methodVisitor.visitCode();

    // GENERATE super.<setter>(v)

    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(paramType.getOpcode(Opcodes.ILOAD), 1);

    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), setter.getName(), setterDescriptor, false);

    // END

    // GENERATE __<prop>__ = true

    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitLdcInsn(true);
    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedType.getInternalName(), propFieldName(property), Type.BOOLEAN_TYPE.getDescriptor());

    // END

    methodVisitor.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:31,代码来源:AsmBackedClassGenerator.java

示例4: writeGenericReturnTypeFieldInitializer

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
private void writeGenericReturnTypeFieldInitializer(MethodVisitor mv, ReturnTypeEntry returnType) {
    mv.visitLdcInsn(generatedType);

    // <class>.getDeclaredMethod(<getter-name>)
    mv.visitLdcInsn(returnType.getterName);
    mv.visitInsn(Opcodes.ICONST_0);
    mv.visitTypeInsn(Opcodes.ANEWARRAY, CLASS_TYPE.getInternalName());
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CLASS_TYPE.getInternalName(), "getDeclaredMethod", GET_DECLARED_METHOD_DESCRIPTOR, false);
    // <method>.getGenericReturnType()
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, METHOD_TYPE.getInternalName(), "getGenericReturnType", Type.getMethodDescriptor(JAVA_LANG_REFLECT_TYPE), false);
    mv.visitFieldInsn(PUTSTATIC, generatedType.getInternalName(), returnType.fieldName, JAVA_REFLECT_TYPE_DESCRIPTOR);

}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:14,代码来源:AsmBackedClassGenerator.java

示例5: addBooleanGetGetter

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
private void addBooleanGetGetter(String booleanField) {
    MethodVisitor mv = cv.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, "get" + StringUtils.capitalize(booleanField), "()Z", null, null);
    mv.visitCode();
    Label l0 = new Label();
    mv.visitLabel(l0);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitFieldInsn(Opcodes.GETFIELD, className, booleanField, "Z");
    mv.visitInsn(Opcodes.IRETURN);
    Label l1 = new Label();
    mv.visitLabel(l1);
    mv.visitLocalVariable("this", "L" + className + ";", null, l0, l1, 0);
    mv.visitMaxs(1, 1);
    mv.visitEnd();
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:15,代码来源:MixInLegacyTypesClassLoader.java

示例6: hookMethod

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
/**
 * (none-javadoc)
 *
 * @see com.fuxi.javaagent.hook.AbstractClassHook#hookMethod(int, String, String, String, String[], MethodVisitor)
 */
@Override
protected MethodVisitor hookMethod(int access, String name, String desc, String signature, String[] exceptions, MethodVisitor mv) {
    // store file info in lockClose Object
    if ("<init>".equals(name) && "(Ljava/io/File;Z)V".equals(desc)) {
        return new AdviceAdapter(Opcodes.ASM5, mv, access, name, desc) {
            @Override
            public void onMethodExit(int opcode) {
                if (opcode == Opcodes.RETURN) {
                    mv.visitVarInsn(ALOAD, 0);
                    mv.visitTypeInsn(NEW, "com/fuxi/javaagent/tool/hook/CustomLockObject");
                    mv.visitInsn(DUP);
                    mv.visitMethodInsn(INVOKESPECIAL, "com/fuxi/javaagent/tool/hook/CustomLockObject",
                            "<init>", "()V", false);
                    mv.visitFieldInsn(PUTFIELD, "java/io/FileOutputStream", "closeLock", "Ljava/lang/Object;");
                    mv.visitVarInsn(ALOAD, 0);
                    mv.visitFieldInsn(GETFIELD, "java/io/FileOutputStream", "closeLock", "Ljava/lang/Object;");
                    mv.visitVarInsn(ALOAD, 3);
                    mv.visitMethodInsn(INVOKESTATIC, "com/fuxi/javaagent/hook/file/FileOutputStream2Hook", "checkFileOutputStreamInit",
                            "(Ljava/lang/Object;Ljava/lang/String;)V", false);
                }
                super.onMethodExit(opcode);
            }
        };
    }
    if (name.equals("write") && desc.startsWith("([B")) {
        return new AdviceAdapter(Opcodes.ASM5, mv, access, name, desc) {
            @Override
            public void onMethodEnter() {
                mv.visitVarInsn(ALOAD, 0);
                mv.visitFieldInsn(GETFIELD, "java/io/FileOutputStream", "closeLock", "Ljava/lang/Object;");
                mv.visitVarInsn(ALOAD, 1);
                mv.visitMethodInsn(INVOKESTATIC, "com/fuxi/javaagent/hook/file/FileOutputStream2Hook", "checkFileOutputStreamWrite",
                        "(Ljava/lang/Object;[B)V", false);
            }
        };
    }
    return mv;
}
 
开发者ID:baidu,项目名称:openrasp,代码行数:44,代码来源:FileOutputStream2Hook.java

示例7: test

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
@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();

}
 
开发者ID:alibaba,项目名称:atlas,代码行数:73,代码来源:AsmTest.java

示例8: buildClosureClass

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
private void buildClosureClass(TContext closure_ctx) throws CompileException {
  Debug.assertion(closure_ctx instanceof TContextClosure, "closure_ctx should be closure ctx");

  ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
  ((TContextClosure) closure_ctx).setClassWriter(cw);

  cw.visit(Compiler.java_version, Opcodes.ACC_PUBLIC, closure_ctx.getName(), null, "java/lang/Object", null);

  // default constructor
  MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
  mv.visitCode();

  LOG.info("ALOAD 0 for this");
  LOG.info("INVOKESPECIAL java/lang/Object");

  mv.visitVarInsn(Opcodes.ALOAD, 0); // this
  mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
  if (Debug.enable_compile_debug_print) {
    mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
    mv.visitLdcInsn(closure_ctx.getName() + " was instantiated");
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false);
  }
  mv.visitInsn(Opcodes.RETURN);
  mv.visitMaxs(0, 0);
  mv.visitEnd();
  // end default constructor

  TContext parent_ctx = (TContext) closure_ctx.getOwnerType();
  Debug.assertion(parent_ctx != null, "parent_ctx should be valid");

  // add closure class member field
  Container var_cont = null;
  AbsType var_type = null;

  LinkedList<Container> var_list = closure_ctx.get_childvar_list();
  int var_size = var_list.size();
  Container closure_member_var = null;

  for (int i = 0; i < var_size; i++) {
    closure_member_var = var_list.get(i);
    var_cont = closure_member_var.getClosureOrgFuncvarContainer();

    Debug.assertion(var_cont != null, "var_cont should be valid");
    // Debug.assertion(var_cont.isForm(Container.FORM_FUNSTACK_VAR), "var_cont
    // should be stack variable");
    Debug.assertion(var_cont.isTypeInitialized(), "var_cont type should be initialized");

    if (var_cont.isForm(Container.FORM_FUNSTACK_VAR)) {
      // only assigned stack variable will be copied
      if (var_cont.isAssigned()) {
        LOG.debug("  (" + var_cont.getContextVarIdx() + ") " + var_cont);
        var_type = var_cont.getType();
        cw.visitField(Opcodes.ACC_PUBLIC, var_cont.getName(), var_type.getMthdDscStr(), null, null).visitEnd();
      }
    } else if (var_cont.isForm(Container.FORM_OBJMEMBER_VAR)) {
      LOG.debug("  (" + var_cont.getContextVarIdx() + ") " + var_cont);
      var_type = var_cont.getType();
      cw.visitField(Opcodes.ACC_PUBLIC, var_cont.getName(), var_type.getMthdDscStr(), null, null).visitEnd();
    } else {
      throw new CompileException("Invalid var_cont form(" + var_cont + ")");
    }

  }

}
 
开发者ID:Samsung,项目名称:MeziLang,代码行数:66,代码来源:ASTCompileVisitor.java

示例9: insertGetString

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
static private void insertGetString(ClassWriter cw, String classNameInternal, ArrayList<Field> fields) {
	int maxStack = 6;
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "getString", "(Ljava/lang/Object;I)Ljava/lang/String;", null,
			null);
	mv.visitCode();
	mv.visitVarInsn(ILOAD, 2);

	if (!fields.isEmpty()) {
		maxStack--;
		Label[] labels = new Label[fields.size()];
		Label labelForInvalidTypes = new Label();
		boolean hasAnyBadTypeLabel = false;
		for (int i = 0, n = labels.length; i < n; i++) {
			if (fields.get(i).getType().equals(String.class))
				labels[i] = new Label();
			else {
				labels[i] = labelForInvalidTypes;
				hasAnyBadTypeLabel = true;
			}
		}
		Label defaultLabel = new Label();
		mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

		for (int i = 0, n = labels.length; i < n; i++) {
			if (!labels[i].equals(labelForInvalidTypes)) {
				mv.visitLabel(labels[i]);
				mv.visitFrame(F_SAME, 0, null, 0, null);
				mv.visitVarInsn(ALOAD, 1);
				mv.visitTypeInsn(CHECKCAST, classNameInternal);
				mv.visitFieldInsn(GETFIELD, classNameInternal, fields.get(i).getName(), "Ljava/lang/String;");
				mv.visitInsn(ARETURN);
			}
		}
		// Rest of fields: different type
		if (hasAnyBadTypeLabel) {
			mv.visitLabel(labelForInvalidTypes);
			mv.visitFrame(F_SAME, 0, null, 0, null);
			insertThrowExceptionForFieldType(mv, "String");
		}
		// Default: field not found
		mv.visitLabel(defaultLabel);
		mv.visitFrame(F_SAME, 0, null, 0, null);
	}
	insertThrowExceptionForFieldNotFound(mv);
	mv.visitMaxs(maxStack, 3);
	mv.visitEnd();
}
 
开发者ID:HankXV,项目名称:Limitart,代码行数:48,代码来源:FieldAccess.java

示例10: accept

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
@Override
public void accept(final MethodVisitor mv) {
    mv.visitFieldInsn(opcode, owner, name, desc);
    acceptAnnotations(mv);
}
 
开发者ID:ItzSomebody,项目名称:Spigot-Nonce-ID-Finder,代码行数:6,代码来源:FieldInsnNode.java

示例11: assignStateField

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
private void assignStateField(MethodVisitor constructorVisitor, Type generatedType) {
    putThisOnStack(constructorVisitor);
    putFirstMethodArgumentOnStack(constructorVisitor);
    constructorVisitor.visitFieldInsn(PUTFIELD, generatedType.getInternalName(), STATE_FIELD_NAME, GENERATED_VIEW_STATE_TYPE.getDescriptor());
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:6,代码来源:ManagedProxyClassGenerator.java

示例12: insertSetObject

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
@SuppressWarnings("deprecation")
static private void insertSetObject(ClassWriter cw, String classNameInternal, ArrayList<Field> fields) {
	int maxStack = 6;
	MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "set", "(Ljava/lang/Object;ILjava/lang/Object;)V", null, null);
	mv.visitCode();
	mv.visitVarInsn(ILOAD, 2);

	if (!fields.isEmpty()) {
		maxStack--;
		Label[] labels = new Label[fields.size()];
		for (int i = 0, n = labels.length; i < n; i++)
			labels[i] = new Label();
		Label defaultLabel = new Label();
		mv.visitTableSwitchInsn(0, labels.length - 1, defaultLabel, labels);

		for (int i = 0, n = labels.length; i < n; i++) {
			Field field = fields.get(i);
			Type fieldType = Type.getType(field.getType());

			mv.visitLabel(labels[i]);
			mv.visitFrame(F_SAME, 0, null, 0, null);
			mv.visitVarInsn(ALOAD, 1);
			mv.visitTypeInsn(CHECKCAST, classNameInternal);
			mv.visitVarInsn(ALOAD, 3);

			switch (fieldType.getSort()) {
			case Type.BOOLEAN:
				mv.visitTypeInsn(CHECKCAST, "java/lang/Boolean");
				mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z");
				break;
			case Type.BYTE:
				mv.visitTypeInsn(CHECKCAST, "java/lang/Byte");
				mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B");
				break;
			case Type.CHAR:
				mv.visitTypeInsn(CHECKCAST, "java/lang/Character");
				mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C");
				break;
			case Type.SHORT:
				mv.visitTypeInsn(CHECKCAST, "java/lang/Short");
				mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Short", "shortValue", "()S");
				break;
			case Type.INT:
				mv.visitTypeInsn(CHECKCAST, "java/lang/Integer");
				mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I");
				break;
			case Type.FLOAT:
				mv.visitTypeInsn(CHECKCAST, "java/lang/Float");
				mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Float", "floatValue", "()F");
				break;
			case Type.LONG:
				mv.visitTypeInsn(CHECKCAST, "java/lang/Long");
				mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Long", "longValue", "()J");
				break;
			case Type.DOUBLE:
				mv.visitTypeInsn(CHECKCAST, "java/lang/Double");
				mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D");
				break;
			case Type.ARRAY:
				mv.visitTypeInsn(CHECKCAST, fieldType.getDescriptor());
				break;
			case Type.OBJECT:
				mv.visitTypeInsn(CHECKCAST, fieldType.getInternalName());
				break;
			}

			mv.visitFieldInsn(PUTFIELD, classNameInternal, field.getName(), fieldType.getDescriptor());
			mv.visitInsn(RETURN);
		}

		mv.visitLabel(defaultLabel);
		mv.visitFrame(F_SAME, 0, null, 0, null);
	}
	mv = insertThrowExceptionForFieldNotFound(mv);
	mv.visitMaxs(maxStack, 4);
	mv.visitEnd();
}
 
开发者ID:HankXV,项目名称:Limitart,代码行数:78,代码来源:FieldAccess.java

示例13: assignDelegateField

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
private void assignDelegateField(MethodVisitor constructorVisitor, Type generatedType, Type delegateType) {
    putThisOnStack(constructorVisitor);
    putThirdMethodArgumentOnStack(constructorVisitor);
    constructorVisitor.visitFieldInsn(PUTFIELD, generatedType.getInternalName(), DELEGATE_FIELD_NAME, delegateType.getDescriptor());
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:6,代码来源:ManagedProxyClassGenerator.java

示例14: setCanCallSettersField

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
private void setCanCallSettersField(MethodVisitor methodVisitor, Type generatedType, boolean canCallSetters) {
    putThisOnStack(methodVisitor);
    methodVisitor.visitLdcInsn(canCallSetters);
    methodVisitor.visitFieldInsn(PUTFIELD, generatedType.getInternalName(), CAN_CALL_SETTERS_FIELD_NAME, Type.BOOLEAN_TYPE.getDescriptor());
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:6,代码来源:ManagedProxyClassGenerator.java

示例15: applyServiceInjectionToGetter

import org.objectweb.asm.MethodVisitor; //导入方法依赖的package包/类
public void applyServiceInjectionToGetter(PropertyMetaData property, Method getter) throws Exception {
    // GENERATE public <type> <getter>() { if (<field> == null) { <field> = getServices().get(getClass().getDeclaredMethod(<getter-name>).getGenericReturnType()); } return <field> }
    String getterName = getter.getName();
    Type returnType = Type.getType(getter.getReturnType());
    String methodDescriptor = Type.getMethodDescriptor(returnType);
    Type serviceType = Type.getType(property.getType());
    String propFieldName = propFieldName(property);

    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, getterName, methodDescriptor, signature(getter), EMPTY_STRINGS);
    methodVisitor.visitCode();

    // if (this.<field> == null) { ...  }

    // this.field
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, generatedType.getInternalName(), propFieldName, serviceType.getDescriptor());

    Label alreadyLoaded = new Label();
    methodVisitor.visitJumpInsn(Opcodes.IFNONNULL, alreadyLoaded);

    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);

    // this.getServices()
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, generatedType.getInternalName(), "getServices", Type.getMethodDescriptor(SERVICE_REGISTRY_TYPE), false);

    java.lang.reflect.Type genericReturnType = getter.getGenericReturnType();
    if (genericReturnType instanceof Class) {
        // if the return type doesn't use generics, then it's faster to just rely on the type name directly
        methodVisitor.visitLdcInsn(Type.getType((Class) genericReturnType));
    } else {
        // load the static type descriptor from class constants
        String constantFieldName = getConstantNameForGenericReturnType(genericReturnType, getterName);
        methodVisitor.visitFieldInsn(GETSTATIC, generatedType.getInternalName(), constantFieldName, JAVA_REFLECT_TYPE_DESCRIPTOR);
    }

    // get(<type>)
    methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, SERVICE_REGISTRY_TYPE.getInternalName(), "get", GET_METHOD_DESCRIPTOR, true);

    // this.field = (<type>)<service>
    methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, serviceType.getInternalName());
    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedType.getInternalName(), propFieldName, serviceType.getDescriptor());

    // this.field
    methodVisitor.visitLabel(alreadyLoaded);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitFieldInsn(Opcodes.GETFIELD, generatedType.getInternalName(), propFieldName, serviceType.getDescriptor());

    // return
    methodVisitor.visitInsn(returnType.getOpcode(Opcodes.IRETURN));
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:54,代码来源:AsmBackedClassGenerator.java


注:本文中的org.objectweb.asm.MethodVisitor.visitFieldInsn方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。