Java中的Class.getArrayType? [英] Class.getArrayType in Java?

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

问题描述

我使用以下技巧来获取特定类的数组类型:

I use the following trick to get the array type of a specific class:

@SuppressWarnings("unchecked")
public static <T> Class<T[]> getArrayType(Class<T> componentType) {
    String arrayClassName = "[L" + componentType.getName() + ";";
    try {
        return (Class<T[]>) Class.forName(arrayClassName);
    } catch (ClassNotFoundException e) {
        throw new UnexpectedException("Can't get the array type for " + componentType, e);
    }
}

但是,有没有更优雅的方式来获得这个?

But, is there any more elegant way to get this?

推荐答案

也许使用

Perhaps using Array.newInstance(), which returns an array of a given type.

做类似的事情:

return Array.newInstance(someClass, 0).getClass()

可能会为您带来想要的东西.

Might get you what you want.

希望有帮助.

这篇关于Java中的Class.getArrayType?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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