[英]Creating java class with annotated fields in runtime
問題是我需要在運行時中創建一個像這樣的類:
public class Foo {
@Bar int value0;
@Bar int value1;
@Bar int value2;
....
}
在運行時確定字段數。
我正在查看Javassist,在那里您可以創建一個新類,並向其中添加字段,但是我還沒有找到注釋這些字段的方法。
您可以使用類似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()));
}
}
}
輸出:
int Foo.value0 [@Bar()]
int Foo.value1 [@Bar()]
int Foo.value2 [@Bar()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.