Java Code Examples for org.objectweb.asm.ClassWriter#visitAnnotation()

The following examples show how to use org.objectweb.asm.ClassWriter#visitAnnotation() . 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: DynamicEntityGenerator.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
private static void writeClass(String classDesc, String tabelName, String className, ClassWriter classWriter) {
    AnnotationVisitor annotationVisitor0;
    classWriter.visit(V1_8, ACC_PUBLIC | ACC_SUPER, classDesc, null, "java/lang/Object", new String[] { "java/io/Serializable" });

    annotationVisitor0 = classWriter.visitAnnotation("Ljavax/persistence/Entity;", true);
    annotationVisitor0.visitEnd();

    annotationVisitor0 = classWriter.visitAnnotation("Ljavax/persistence/Table;", true);
    annotationVisitor0.visit("name", tabelName);
    annotationVisitor0.visitEnd();

    annotationVisitor0 = classWriter.visitAnnotation("Ljavax/persistence/NamedQuery;", true);
    annotationVisitor0.visit("name", className + ".findAll");
    annotationVisitor0.visit("query", "SELECT a FROM " + className + " a");
    annotationVisitor0.visitEnd();
}
 
Example 2
Source File: DefaultApplicationFactory.java    From thorntail with Apache License 2.0 6 votes vote down vote up
public static byte[] create(String name, String path) throws IOException {
    ClassReader reader = new ClassReader(basicClassBytes());

    String slashName = name.replace('.', '/');

    ClassWriter writer = new ClassWriter(0);
    Remapper remapper = new Remapper() {
        @Override
        public String map(String typeName) {
            if (typeName.equals("org/wildfly/swarm/jaxrs/runtime/DefaultApplication")) {
                return slashName;
            }
            return super.map(typeName);
        }
    };

    ClassRemapper adapter = new ClassRemapper(writer, remapper);
    reader.accept(adapter, 0);

    AnnotationVisitor ann = writer.visitAnnotation("Ljavax/ws/rs/ApplicationPath;", true);
    ann.visit("value", path);
    ann.visitEnd();
    writer.visitEnd();

    return writer.toByteArray();
}
 
Example 3
Source File: ApplicationFactory2.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 6 votes vote down vote up
static byte[] create(String name, String path) throws IOException {
    ClassReader reader = new ClassReader(DefaultApplication.class.getClassLoader().getResourceAsStream(DefaultApplication.class.getName().replace('.', '/') + ".class"));

    String slashName = name.replace('.', '/');

    ClassWriter writer = new ClassWriter(0);
    Remapper remapper = new Remapper() {
        @Override
        public String map(String typeName) {
            if (typeName.equals("org/wildfly/swarm/jaxrs/internal/DefaultApplication")) {
                return slashName;
            }
            return super.map(typeName);
        }
    };

    RemappingClassAdapter adapter = new RemappingClassAdapter(writer, remapper);
    reader.accept(adapter, 0);

    AnnotationVisitor ann = writer.visitAnnotation("Ljavax/ws/rs/ApplicationPath;", true);
    ann.visit("value", path);
    ann.visitEnd();
    writer.visitEnd();

    return writer.toByteArray();
}
 
Example 4
Source File: DynamicClassFactory.java    From caravan with Apache License 2.0 5 votes vote down vote up
private Class<?> createClass(ClassPair classPair) {
  String className = generateClassName(classPair);
  String classStr = className.replaceAll("\\.", "/");

  String keyClassType = Type.getDescriptor(classPair.keyClass);
  String valueClassType = Type.getDescriptor(classPair.valueClass);

  ClassWriter cw = new ClassWriter(0);
  cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, className, null, "java/lang/Object", new String[]{interfaceName});

  AnnotationVisitor anno = cw.visitAnnotation(Type.getDescriptor(JsonPropertyOrder.class), true);
  AnnotationVisitor aa = anno.visitArray("value");
  aa.visit("", "key");
  aa.visit("", "value");
  aa.visitEnd();
  anno.visitEnd();

  FieldVisitor keyField = cw.visitField(ACC_PRIVATE, "key", keyClassType, null, null);
  keyField.visitEnd();

  FieldVisitor valueField = cw.visitField(ACC_PRIVATE, "value", valueClassType, null, null);
  valueField.visitEnd();

  MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
  mv.visitMaxs(2, 1);
  mv.visitVarInsn(ALOAD, 0);
  mv.visitMethodInsn(INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V", false); // call the constructor of super class
  mv.visitInsn(RETURN);
  mv.visitEnd();

  addGetterSetter(classPair, className, classStr, keyClassType, valueClassType, cw);
  addKVPairMethods(classPair, className, classStr, keyClassType, valueClassType, cw);

  cw.visitEnd();

  return defineClass(className, cw.toByteArray());
}
 
Example 5
Source File: ClassReaderTest.java    From turbine with Apache License 2.0 5 votes vote down vote up
@Test
public void annotationDeclaration() {
  ClassWriter cw = new ClassWriter(0);
  cw.visit(
      52,
      Opcodes.ACC_PUBLIC + Opcodes.ACC_ANNOTATION + Opcodes.ACC_ABSTRACT + Opcodes.ACC_INTERFACE,
      "test/Hello",
      null,
      "java/lang/Object",
      new String[] {"java/lang/annotation/Annotation"});
  AnnotationVisitor av = cw.visitAnnotation("Ljava/lang/annotation/Retention;", true);
  av.visitEnum("value", "Ljava/lang/annotation/RetentionPolicy;", "RUNTIME");
  av.visitEnd();
  cw.visitEnd();
  byte[] bytes = cw.toByteArray();

  ClassFile classFile = com.google.turbine.bytecode.ClassReader.read(null, bytes);

  assertThat(classFile.access())
      .isEqualTo(
          TurbineFlag.ACC_PUBLIC
              | TurbineFlag.ACC_ANNOTATION
              | TurbineFlag.ACC_ABSTRACT
              | TurbineFlag.ACC_INTERFACE);
  assertThat(classFile.name()).isEqualTo("test/Hello");
  assertThat(classFile.signature()).isNull();
  assertThat(classFile.superName()).isEqualTo("java/lang/Object");
  assertThat(classFile.interfaces()).containsExactly("java/lang/annotation/Annotation");

  assertThat(classFile.annotations()).hasSize(1);
  ClassFile.AnnotationInfo annotation = Iterables.getOnlyElement(classFile.annotations());
  assertThat(annotation.typeName()).isEqualTo("Ljava/lang/annotation/Retention;");
  assertThat(annotation.elementValuePairs()).hasSize(1);
  assertThat(annotation.elementValuePairs()).containsKey("value");
  ElementValue value = annotation.elementValuePairs().get("value");
  assertThat(value.kind()).isEqualTo(ElementValue.Kind.ENUM);
  ElementValue.EnumConstValue enumValue = (ElementValue.EnumConstValue) value;
  assertThat(enumValue.typeName()).isEqualTo("Ljava/lang/annotation/RetentionPolicy;");
  assertThat(enumValue.constName()).isEqualTo("RUNTIME");
}
 
Example 6
Source File: ClassReaderTest.java    From turbine with Apache License 2.0 5 votes vote down vote up
@Test
public void v53() {
  ClassWriter cw = new ClassWriter(0);
  cw.visitAnnotation("Ljava/lang/Deprecated;", true);
  cw.visit(
      53,
      Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SUPER,
      "Hello",
      null,
      "java/lang/Object",
      null);
  ClassFile cf = ClassReader.read(null, cw.toByteArray());
  assertThat(cf.name()).isEqualTo("Hello");
}
 
Example 7
Source File: AdviceGenerator.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void addClassAnnotation(ClassWriter cw) {
    AnnotationVisitor annotationVisitor =
            cw.visitAnnotation("Lorg/glowroot/agent/plugin/api/weaving/Pointcut;", true);
    annotationVisitor.visit("className", config.className());
    annotationVisitor.visit("classAnnotation", config.classAnnotation());
    annotationVisitor.visit("subTypeRestriction", config.subTypeRestriction());
    annotationVisitor.visit("superTypeRestriction", config.superTypeRestriction());
    annotationVisitor.visit("methodName", config.methodName());
    annotationVisitor.visit("methodAnnotation", config.methodAnnotation());
    AnnotationVisitor arrayAnnotationVisitor =
            checkNotNull(annotationVisitor.visitArray("methodParameterTypes"));
    for (String methodParameterType : config.methodParameterTypes()) {
        arrayAnnotationVisitor.visit(null, methodParameterType);
    }
    arrayAnnotationVisitor.visitEnd();
    String timerName = config.timerName();
    if (config.isTimerOrGreater()) {
        if (timerName.isEmpty()) {
            annotationVisitor.visit("timerName", "<no timer name provided>");
        } else {
            annotationVisitor.visit("timerName", timerName);
        }
    }
    String nestingGroup = config.nestingGroup();
    if (!nestingGroup.isEmpty()) {
        annotationVisitor.visit("nestingGroup", nestingGroup);
    } else if (!config.traceEntryCaptureSelfNested()) {
        annotationVisitor.visit("nestingGroup", "__GeneratedAdvice" + uniqueNum);
    }
    annotationVisitor.visit("order", config.order());
    annotationVisitor.visitEnd();
}
 
Example 8
Source File: ModClassGenerator.java    From customstuff4 with GNU General Public License v3.0 4 votes vote down vote up
private static byte[] generateClassCode(ModInfo info)
{
    checkArgument(info.isValid(), "Invalid mod id");

    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER, "cs4mod/" + info.id, null, "java/lang/Object", new String[] {CS4_MOD});

    // Mod annotation
    AnnotationVisitor av = cw.visitAnnotation(String.format("L%s;", MOD), true);
    av.visit("modid", info.id);
    av.visit("name", info.name);
    av.visit("version", info.version);
    av.visit("dependencies", String.format("required-after:%s;%s", CustomStuff4.ID, info.dependencies));
    av.visitEnd();

    // Constructor
    MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
    mv.visitFieldInsn(GETSTATIC, "net/minecraftforge/common/MinecraftForge", "EVENT_BUS", desc(EVENT_BUS));
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKEVIRTUAL, EVENT_BUS, "register", voidMethodDesc("java/lang/Object"), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(2, 1);
    mv.visitEnd();

    // PreInit
    mv = cw.visitMethod(ACC_PUBLIC, "preInit", voidMethodDesc(PRE_INIT_EVENT), null, null);
    av = mv.visitAnnotation(String.format("L%s;", EVENT_HANDLER), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onPreInitMod", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // Init
    mv = cw.visitMethod(ACC_PUBLIC, "init", voidMethodDesc(INIT_EVENT), null, null);
    av = mv.visitAnnotation(String.format("L%s;", EVENT_HANDLER), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onInitMod", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // PostInit
    mv = cw.visitMethod(ACC_PUBLIC, "postInit", voidMethodDesc(POST_INIT_EVENT), null, null);
    av = mv.visitAnnotation(String.format("L%s;", EVENT_HANDLER), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onPostInitMod", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // RegisterBlocks
    mv = cw.visitMethod(ACC_PUBLIC, "onRegisterBlocks", voidMethodDesc(REGISTER_BLOCKS_EVENT), voidMethodDesc(REGISTER_BLOCKS_SIGNATURE), null);
    av = mv.visitAnnotation(desc(SUBSCRIBE_EVENT), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onRegisterBlocks", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // RegisterItems
    mv = cw.visitMethod(ACC_PUBLIC, "onRegisterItems", voidMethodDesc(REGISTER_ITEMS_EVENT), voidMethodDesc(REGISTER_ITEMS_SIGNATURE), null);
    av = mv.visitAnnotation(desc(SUBSCRIBE_EVENT), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onRegisterItems", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    // RegisterModels
    mv = cw.visitMethod(ACC_PUBLIC, "onRegisterModels", voidMethodDesc(REGISTER_MODELS_EVENT), null, null);
    av = mv.visitAnnotation(desc(SUBSCRIBE_EVENT), true);
    av.visitEnd();
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESTATIC, MOD_LOADER, "onRegisterModels", voidMethodDesc(CS4_MOD), false);
    mv.visitInsn(RETURN);
    mv.visitMaxs(1, 2);
    mv.visitEnd();

    return cw.toByteArray();
}
 
Example 9
Source File: ClassReaderTest.java    From turbine with Apache License 2.0 4 votes vote down vote up
@Test
public void methods() {
  ClassWriter cw = new ClassWriter(0);
  cw.visitAnnotation("Ljava/lang/Deprecated;", true);
  cw.visit(
      52,
      Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL | Opcodes.ACC_SUPER,
      "test/Hello",
      null,
      "java/lang/Object",
      null);
  cw.visitMethod(
      Opcodes.ACC_PUBLIC,
      "f",
      "(Ljava/lang/String;)Ljava/lang/String;",
      "<T:Ljava/lang/String;>(TT;)TT;",
      null);
  cw.visitMethod(
      Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
      "g",
      "(Z)V",
      "<T:Ljava/lang/Error;>(Z)V^TT;",
      new String[] {"java/lang/Error"});
  cw.visitMethod(0, "h", "(I)V", null, null);
  byte[] bytes = cw.toByteArray();

  ClassFile classFile = com.google.turbine.bytecode.ClassReader.read(null, bytes);

  assertThat(classFile.access())
      .isEqualTo(TurbineFlag.ACC_PUBLIC | TurbineFlag.ACC_FINAL | TurbineFlag.ACC_SUPER);
  assertThat(classFile.name()).isEqualTo("test/Hello");
  assertThat(classFile.signature()).isNull();
  assertThat(classFile.superName()).isEqualTo("java/lang/Object");
  assertThat(classFile.interfaces()).isEmpty();

  assertThat(classFile.methods()).hasSize(3);

  ClassFile.MethodInfo f = classFile.methods().get(0);
  assertThat(f.access()).isEqualTo(TurbineFlag.ACC_PUBLIC);
  assertThat(f.name()).isEqualTo("f");
  assertThat(f.descriptor()).isEqualTo("(Ljava/lang/String;)Ljava/lang/String;");
  assertThat(f.signature()).isEqualTo("<T:Ljava/lang/String;>(TT;)TT;");
  assertThat(f.exceptions()).isEmpty();
  assertThat(f.annotations()).isEmpty();
  assertThat(f.parameterAnnotations()).isEmpty();
  assertThat(f.defaultValue()).isNull();

  ClassFile.MethodInfo g = classFile.methods().get(1);
  assertThat(g.access()).isEqualTo(TurbineFlag.ACC_PUBLIC | TurbineFlag.ACC_STATIC);
  assertThat(g.name()).isEqualTo("g");
  assertThat(g.descriptor()).isEqualTo("(Z)V");
  assertThat(g.signature()).isEqualTo("<T:Ljava/lang/Error;>(Z)V^TT;");

  ClassFile.MethodInfo h = classFile.methods().get(2);
  assertThat(h.access()).isEqualTo(0);
  assertThat(h.name()).isEqualTo("h");
  assertThat(h.descriptor()).isEqualTo("(I)V");
  assertThat(h.signature()).isNull();
}
 
Example 10
Source File: ClientServiceFactory.java    From thorntail with Apache License 2.0 4 votes vote down vote up
static byte[] createImpl(String implName, ClassInfo classInfo) {
    ClassWriter cw = new ClassWriter(0);
    MethodVisitor mv;
    AnnotationVisitor av0;

    cw.visit(V1_8, ACC_PUBLIC + ACC_SUPER,
             implName.replace('.', '/'),
             null,
             "java/lang/Object",
             new String[]{classInfo.name().toString().replace('.', '/')}
    );

    int lastDot = implName.lastIndexOf('.');
    String simpleName = implName.substring(lastDot + 1);

    cw.visitSource(simpleName + ".java", null);
    {
        av0 = cw.visitAnnotation("Ljavax/enterprise/context/ApplicationScoped;", true);
        av0.visitEnd();
    }
    cw.visitInnerClass("javax/ws/rs/client/Invocation$Builder", "javax/ws/rs/client/Invocation", "Builder", ACC_PUBLIC + ACC_STATIC + ACC_ABSTRACT + ACC_INTERFACE);

    {
        mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        Label l0 = new Label();
        mv.visitLabel(l0);
        mv.visitLineNumber(14, l0);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        Label l1 = new Label();
        mv.visitLabel(l1);
        mv.visitLineNumber(15, l1);
        mv.visitInsn(RETURN);
        Label l2 = new Label();
        mv.visitLabel(l2);
        mv.visitLocalVariable("this",
                              buildTypeDef(implName),
                              null,
                              l0,
                              l2,
                              0);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }

    List<AnnotationInstance> annotations = classInfo.annotations().get(DotName.createSimple("org.wildfly.swarm.client.jaxrs.Service"));
    String baseUrl = (String) annotations.get(0).value("baseUrl").value();
    int lineNum = 18;

    classInfo.asClass().methods()
            .stream()
            .forEachOrdered(method -> {
                createMethod(cw, implName, classInfo.name().toString(), method, lineNum, baseUrl);
            });
    cw.visitEnd();

    return cw.toByteArray();
}
 
Example 11
Source File: ApplicationFactory.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 4 votes vote down vote up
public static byte[] create(String name, String context) {

        ClassWriter cw = new ClassWriter(0);
        MethodVisitor mv;
        AnnotationVisitor av0;

        cw.visit(V1_7, ACC_PUBLIC + ACC_SUPER,
                name.replace('.', '/'),
                null,
                "javax/ws/rs/core/Application", null);

        int lastDot = name.lastIndexOf('.');
        String simpleName = name.substring(lastDot + 1);
        cw.visitSource(simpleName + ".java", null);

        {
            av0 = cw.visitAnnotation("Ljavax/ws/rs/ApplicationPath;", true);
            av0.visit("value", "/");
            av0.visitEnd();
        }
        {
            mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            Label l0 = new Label();
            mv.visitLabel(l0);
            mv.visitLineNumber(10, l0);
            mv.visitVarInsn(ALOAD, 0);
            mv.visitMethodInsn(INVOKESPECIAL, "javax/ws/rs/core/Application", "<init>", "()V", false);
            mv.visitInsn(RETURN);
            Label l1 = new Label();
            mv.visitLabel(l1);
            mv.visitLocalVariable("this",
                    "L" + name.replace('.', '/') + ";",
                    null,
                    l0,
                    l1,
                    0);
            mv.visitMaxs(1, 1);
            mv.visitEnd();
        }
        cw.visitEnd();

        return cw.toByteArray();
    }