在Java中,如何动态确定数组的类型? [英] In Java, how do I dynamically determine the type of an array?

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

问题描述

Object o = new Long[0]
System.out.println( o.getClass().isArray() )
System.out.println( o.getClass().getName() )
Class ofArray = ???

运行前3行发出;

true
[Ljava.lang.Long;

我如何得到???打字长?我可以解析字符串并执行Class.forname(),但那很糟糕。什么是简单的方法?

How do I get ??? to be type long? I could parse the string and do a Class.forname(), but thats grotty. What's the easy way?

推荐答案

只需写下

Class ofArray = o.getClass().getComponentType();

来自 JavaDoc


public Class<?> getComponentType()

返回表示数组组件类型的 Class 。如果此类不表示数组类,则此方法返回 null

Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.

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

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