如何在Java中使用反射将字段强制转换为特定类? [英] How to cast field to specific class using reflection in java?
本文介绍了如何在Java中使用反射将字段强制转换为特定类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用反射将所有类型为 Card
类的类的所有成员变量放入 ArrayList< Card>
实例中.如何完成最后一部分(请参见下面的注释行)?
I am using reflection to put all my class's member variables that are of type Card
class into an ArrayList<Card>
instance. How do I finish this last part (see commented line below)?
ArrayList<Card> cardList = new ArrayList<Card>();
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getType() == Card.class) {
//how do I convert 'field' to a 'Card' object and add it to the 'cardList' here?
推荐答案
Field
只是对该字段的描述,而不是其中包含的值.
Field
is just the description of the field, it is not the value contained in there.
您需要先获取该值,然后才能对其进行转换:
You need to first get the value, and then you can cast it:
Card x = (Card) field.get(this);
此外,您可能还希望允许子类,所以您应该这样做
Also, you probably want to allow subclasses as well, so you should do
// if (field.getType() == Card.class) {
if (Card.class.isAssignableFrom(field.getType()) {
这篇关于如何在Java中使用反射将字段强制转换为特定类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文