获取数组类型的Class对象的最佳方法是什么? [英] What's the best way to get a Class object for an array type?
问题描述
为类获取类文字很容易:
It's easy to get a class literal for a class:
String.class
但是如何获得数组类型的类对象?
But how can I get a class object for an array type?
这是有效的,但它很丑,可能不是编译时间常数:
This works, but it's ugly, and probably not a compile time constant:
new byte[0].getClass()
我查看了JLS,但我发现的唯一一件事就是我称之为类文字根据JLS定义,它是一个文字。
I looked in the JLS but the only thing I found out is that what I'm calling a "class literal" isn't a "literal" according to the JLS definition.
推荐答案
您仍然可以使用类文字,即使对于数组类型也是如此。编译得很好。
You can still use a class literal, even for an array type. This compiles just fine.
Class<String[]> clazz = String[].class;
Class<byte[]> clazz2 = byte[].class;
类文字是一个表达式,由类的名称,接口,数组或基本类型组成,或伪类型
void
,后跟一个'。'和令牌class
。
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type
void
, followed by a '.' and the tokenclass
.
(大胆强调我的)
这篇关于获取数组类型的Class对象的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!