简体   繁体   English

Java,如何动态判断数组的类型?

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

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.我可以解析字符串并执行 Class.forname(),但这很糟糕。 What's the easy way?什么是简单的方法?

Just write 写吧

Class ofArray = o.getClass().getComponentType();

From the JavaDoc : JavaDoc

public Class<?> getComponentType()

Returns the Class representing the component type of an array. 返回表示数组的组件类型的Class If this class does not represent an array class this method returns null . 如果此类不表示数组类,则此方法返回null

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. 返回表示数组的组件类型的Class If this class does not represent an array class this method returns null... 如果此类不表示数组类,则此方法返回null。

@ddimitrov is the correct answer. @ddimitrov是正确的答案。 Put into code it looks like this: 放入代码,如下所示:

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 then get 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! 非常简单!

Correct me if im wrong but the [Ltype spec is a defined java standard you can use to figure out the dimensions of a multi dimensional array of type 'type'.如果我错了,请纠正我,但是 [Ltype 规范是定义的 java 标准,您可以使用它来计算类型为“类型”的多维数组的维度。 Just count the brackets.只计算括号。 Yes it's a bit naff compared to the non existent dimensionof operator.是的,与不存在的dimensionof运算符相比,它有点糟糕。 Would love to hear if there is amother way.很想听听是否有其他方式。 A genric way of specifying a method argument as 'array of indeterminate dimension of T' needed?需要一种将方法参数指定为“T 的不确定维度数组”的通用方法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM