java - 在Java中,如何动态判断数组的类型?

标签 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(),但这很糟糕。有什么简单的方法吗?

最佳答案

直接写

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

来自the JavaDoc :

public Class<?> getComponentType()

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

关于java - 在Java中,如何动态判断数组的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44862996/

相关文章:

java - 应用程序运行良好,那么我可以忽略 "CursorWindow: Window is full: requested allocation 12 bytes, free space 4 bytes, window size 2,097,152 bytes"吗?

java - 实现大型二维位数组的最佳方式

java - 当将弱引用或软引用与ReferenceQueue一起使用时,对象何时真正从内存中删除?

带线程的 Java 定时器

java - 如何让我的 JTextArea 或 JTextPane 自动创建一个新行?

java - 如何定义 Eclipse 掩码格式的文本字段?

java - 仅当查询未找到任何结果时才出现错误 java.lang.ClassNotFoundException : org. springframework.orm.jpa.EntityManagerFactoryUtils

java - 特定数字检测器问题

java - Java 中的三维 boolean 数组

java - 在多台机器上运行 tomcat 时的 Quartz 集群设置