简体   繁体   English

在运行时中创建带有注释字段的Java类

[英]Creating java class with annotated fields in runtime

The problem is that I need to create in runtime a class like this: 问题是我需要在运行时中创建一个像这样的类:

public class Foo {
  @Bar int value0;
  @Bar int value1;
  @Bar int value2;
....
}

with number of fields being decided at runtime. 在运行时确定字段数。

I was looking at Javassist, and there you can create a new class, and add fields to it, but I haven't found a way to annotate those fields. 我正在查看Javassist,在那里您可以创建一个新类,并向其中添加字段,但是我还没有找到注释这些字段的方法。

You can use a bytecode manipulation library like ASM : 您可以使用类似ASM的字节码操作库:

import java.lang.reflect.Field;
import java.util.Arrays;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
public class a {
  public static void main(String[] args) throws Exception {
    Class<?> klass = new ClassLoader(a.class.getClassLoader()) {
      public Class<?> defineClass() {
        ClassWriter cw = new ClassWriter(0);
        cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER,
          "Foo", null, "java/lang/Object", null);
        for (int i = 0; i < 3; i++) {
          FieldVisitor fv = cw.visitField(0, "value" + i, "I", null, null);
          fv.visitAnnotation("LBar;", true).visitEnd();
        }
        cw.visitEnd();
        byte[] bytes = cw.toByteArray();
        return defineClass("Foo", bytes, 0, bytes.length);
      }
    }.defineClass();

    for (Field f : klass.getDeclaredFields()) {
      System.out.println(f + " " + Arrays.toString(f.getAnnotations()));
    }
  }
}

Output: 输出:

int Foo.value0 [@Bar()]
int Foo.value1 [@Bar()]
int Foo.value2 [@Bar()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM