【问题标题】:How to get the class associated to an array type?如何获取与数组类型关联的类?
【发布时间】:2014-11-30 19:22:57
【问题描述】:

有没有人知道写以下语句的更好方法:

example.mySpecialMethod(new MySpecialClass[0].getClass())

我需要数组类型,但不知道有没有更好的解决方案。目前这个例子对我有用,但也许有人知道没有new关键字的更好方法。

【问题讨论】:

  • 为什么不MySpecialClass.class ?如果mySpecialMethod()Class 作为参数,那么实例化一个数组是没有意义的。
  • 该方法需要 'Class c' 作为参数

标签: java arrays class new-operator


【解决方案1】:

new MySpecialClass[0] 的类是MySpecialClass[].class,所以你可以使用:

example.mySpecialMethod(MySpecialClass[].class)

【讨论】:

  • 只是出于好奇,如果您的组件类型在编译时未知,那么最好的解决方案是什么?我想不出比java.lang.reflect.Array.newInstance( componentClass, 0 ).getClass()更好的方法了
  • @biziclop 我的代码相当于原来的。但是,如果您需要某个对象的实际类,那么您需要对该对象的引用。
  • 我知道,我只是想到了一个完整的旁白。给定一个数组的类对象,您可以简单地调用getComponentType() 来获取组件类。但反过来似乎要复杂得多。
  • @biziclop:您的问题已经得到解答:Obtaining the array Class of a component type
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 2019-10-25
  • 2020-11-01
  • 2010-12-29
相关资源
最近更新 更多