获取数组类型的 Class 对象的最佳方法是什么? [英] What's the best way to get a Class object for an array type?

查看:23
本文介绍了获取数组类型的 Class 对象的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取类的类文字很容易:

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;

第 15.8.2 节的 JLS 声明:

类字面量是由类名、接口名、数组或原始类型或伪类型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 token class.

(粗体强调我的)

这篇关于获取数组类型的 Class 对象的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆