本文介绍了我可以使用反射在类中添加新字段吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有类文字对象,我可以向类添加新字段吗?我如何确定在该类文字中引用或使用了特定类?
Can I add a new field to a class if I have its class literal object and how can I determine that a particular Class is referenced or used in that class literal ?
推荐答案
您不能直接向 Class
对象添加新字段.您可以使用第三方 API 来生成或修改类(例如 ASM、BCEL),但最好避免使用它们,因为它们会增加很多复杂性.
You can't directly add a new field to the Class
object. There are third-party APIs that you can use to do class generation or modification (e.g. ASM, BCEL), though they're best avoided because they add a lot of complexity.
至于问题的第二部分,您可以使用 Class
对象来浏览字段并检查它们.
As for the second part of your question, you can use the Class
object to go through the fields and examine them.
// 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");
}
}
这篇关于我可以使用反射在类中添加新字段吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!