13

Does anyone know a better way to write the following statement:

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

I need the array type, but I dont know if there is a better solution. At the moment this example works for me, but perhaps someone knows a better way to do the same without the new keyword.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
user3280180
  • 1,393
  • 1
  • 11
  • 27

1 Answers1

17

The class of new MySpecialClass[0] is MySpecialClass[].class so you can use:

example.mySpecialMethod(MySpecialClass[].class)
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Just out of curiosity, what would be the best solution if your component type wasn't known at compile time? I can't think of a better way than `java.lang.reflect.Array.newInstance( componentClass, 0 ).getClass()` – biziclop Oct 06 '14 at 14:00
  • @biziclop my code is equivalent to the original. But if you need the actual class of some object then you need a reference to that object. – assylias Oct 06 '14 at 14:01
  • I know, it just occurred to me as a complete aside. Given a class object of an array, you can simply call `getComponentType()` to get the component class. But the reverse seems to be far more complicated. – biziclop Oct 06 '14 at 14:04
  • 1
    @biziclop: Your question was already answered: [Obtaining the array Class of a component type](http://stackoverflow.com/questions/4901128/obtaining-the-array-class-of-a-component-type). – Jean Hominal Oct 06 '14 at 16:26