在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:27:46  来源:igfitidea点击:

In Java, how do I dynamically determine the type of an array?

java

提问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 Classrepresenting 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 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 Classrepresenting 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!

很直接!