如何确定 Java 中通用字段的类型? [英] How can I determine the type of a generic field in Java?
问题描述
我一直在尝试确定类中字段的类型.我已经看到了所有的内省方法,但还没有完全弄清楚如何去做.这将用于从 Java 类生成 xml/json.我在这里查看了许多问题,但还没有找到我真正需要的.
I have been trying to determine the type of a field in a class. I've seen all the introspection methods but haven't quite figured out how to do it. This is going to be used to generate xml/json from a java class. I've looked at a number of the questions here but haven't found exactly what I need.
示例:
class Person {
public final String name;
public final List<Person> children;
}
当我编组这个对象时,我需要知道 chidren
字段是一个类型为 Person
的对象的列表,这样我才能正确地编组它.
When I marshall this object, I need to know that the chidren
field is a list of objects of type Person
, so I can marshall it properly.
我试过了
for (Field field : Person.class.getDeclaredFields()) {
System.out.format("Type: %s%n", field.getType());
}
但这只会告诉我它是一个List
,而不是Person
s
But this will only tell me that it's a List
, not a List
of Person
s
谢谢
推荐答案
看看 获取字段类型来自 Java 教程 Trail: The反射 API.
Have a look at Obtaining Field Types from the Java Tutorial Trail: The Reflection API.
基本上,您需要做的是获取所有 java.lang.reflect.Field
你的班级 并调用 (检查下面编辑).要获取所有对象字段,包括公共、受保护、包和私有访问字段,只需使用 Field#getType()
在他们每个人上Class.getDeclaredFields()
.像这样:
Basically, what you need to do is to get all java.lang.reflect.Field
of your class and call (check edit below). To get all object fields including public, protected, package and private access fields, simply use Field#getType()
on each of themClass.getDeclaredFields()
. Something like this:
for (Field field : Person.class.getDeclaredFields()) {
System.out.format("Type: %s%n", field.getType());
System.out.format("GenericType: %s%n", field.getGenericType());
}
正如 wowest 在评论中指出的那样,您实际上需要调用Field#getGenericType()
,检查返回的Type
是一个 ParameterizedType
然后相应地获取参数.使用 ParameterizedType#getRawType()
和 ParameterizedType#getActualTypeArgument()
分别获取ParameterizedType
的原始类型和类型参数数组.以下代码演示了这一点:
As pointed out by wowest in a comment, you actually need to call Field#getGenericType()
, check if the returned Type
is a ParameterizedType
and then grab the parameters accordingly. Use ParameterizedType#getRawType()
and ParameterizedType#getActualTypeArgument()
to get the raw type and an array of the types argument of a ParameterizedType
respectively. The following code demonstrates this:
for (Field field : Person.class.getDeclaredFields()) {
System.out.print("Field: " + field.getName() + " - ");
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType)type;
System.out.print("Raw type: " + pType.getRawType() + " - ");
System.out.println("Type args: " + pType.getActualTypeArguments()[0]);
} else {
System.out.println("Type: " + field.getType());
}
}
并且会输出:
Field: name - Type: class java.lang.String
Field: children - Raw type: interface java.util.List - Type args: class foo.Person
这篇关于如何确定 Java 中通用字段的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!