如何在 Java 中获取给定类的数组类? [英] How to get the Array Class for a given Class in Java?

查看:38
本文介绍了如何在 Java 中获取给定类的数组类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保存特定类型的 Class 变量,我需要获取一个保存相应数组类的变量.我能想到的最好的方法是:

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this:

Class arrayOfFooClass = java.lang.reflect.Array.newInstance(fooClass, 0).getClass();

有没有办法在不创建新实例的情况下做到这一点?

Is there a way to do this without creating the new instance?

推荐答案

从 Java 12 开始,就有了 arrayType() java.lang.Class 上的方法.与此:

Since Java 12, there is the arrayType() method on java.lang.Class. With that:

Class<?> arrayOfFooClass = fooClass.arrayType();

这篇关于如何在 Java 中获取给定类的数组类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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