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

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

问题描述

我有一个变量,它保存一个特定的类型,我需要一个变量来保存相应的数组类。最好的我可以想出这是:

 类arrayOfFooClass = java.lang.reflect.Array.newInstance(fooClass,0 ).getClass();有没有办法不用创建新实例呢?


解决方案

如果您不想创建实例,可以手动创建数组的规范名称,并按名称获取类:

  //用对象类型替换String。 
Class stringArrayClass = Class.forName(
[L+ String.class.getCanonicalName()+;
);

Jakob Jenkov在他的博客中说,你的解决方案是更好的一个,因为它不需要用字符串fiddling。

 类stringArrayClass = Array.newInstance(String.class,0).getClass(); 


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?

If you don't want to create an instance, you could create the canonical name of the array manually and get the class by name:

// Replace `String` by your object type.
Class stringArrayClass = Class.forName(
    "[L" + String.class.getCanonicalName() + ";"
);

But Jakob Jenkov argues in his blog that your solution is the better one, because it doesn't need fiddling with strings.

Class stringArrayClass = Array.newInstance(String.class, 0).getClass();

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

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