您无法直接向Class
对象添加新字段.您可以使用第三方API来进行类生成或修改(例如ASM,BCEL),尽管它们最好避免使用,因为它们会增加很多复杂性.
至于问题的第二部分,您可以使用该Class
对象浏览字段并检查它们.
// NOTE : this only looks at the fields in A and not it's superclass.
// you'll have to do a recursive lookup if you want super's fields too.
for(Field field : A.class.getDeclaredFields()) {
if(B.class.equals(field.getType()) {
System.out.println("A." + field.getName() + " is of type B");
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8985 次 |
最近记录: |