在 Java 中,如何动态确定数组的类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/212805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Java, how do I dynamically determine the type of an array?
提问by Bob Herrmann
Object o = new Long[0]
System.out.println( o.getClass().isArray() )
System.out.println( o.getClass().getName() )
Class ofArray = ???
Running the first 3 lines emits;
运行前 3 行会发出;
true
[Ljava.lang.Long;
How do I get ??? to be type long? I could parse the string and do a Class.forname(), but thats grotty. What's the easy way?
如何得到 ???要输入很长吗?我可以解析字符串并执行 Class.forname(),但这太糟糕了。什么是简单的方法?
采纳答案by sakana
Just write
写就好了
Class ofArray = o.getClass().getComponentType();
From the JavaDoc:
从JavaDoc:
public Class<?> getComponentType()
Returns the
Class
representing the component type of an array. If this class does not represent an array class this method returnsnull
.
public Class<?> getComponentType()
返回
Class
表示数组组件类型的 。如果此类不代表数组类,则此方法返回null
。
回答by ddimitrov
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getComponentType():
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getComponentType():
public Class<?> getComponentType()
Returns the
Class
representing the component type of an array. If this class does not represent an array class this method returns null...
public Class<?> getComponentType()
返回
Class
表示数组组件类型的 。如果此类不代表数组类,则此方法返回 null...
回答by Daniel Spiewak
@ddimitrov is the correct answer. Put into code it looks like this:
@ddimitrov 是正确答案。放入代码如下:
public <T> Class<T> testArray(T[] array) {
return array.getClass().getComponentType();
}
Even more generally, we can test first to see if the type represents an array, and thenget its component:
更一般地,我们可以先测试该类型是否代表一个数组,然后获取其组件:
Object maybeArray = ...
Class<?> clazz = maybeArray.getClass();
if (clazz.isArray()) {
System.out.printf("Array of type %s", clazz.getComponentType());
} else {
System.out.println("Not an array");
}
A specific example would be applying this method to an array for which the component type is already known:
一个具体的例子是将此方法应用于组件类型已知的数组:
String[] arr = {"Daniel", "Chris", "Joseph"};
arr.getClass().getComponentType(); // => java.lang.String
Pretty straightforward!
很直接!