Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
Why not MySpecialClass.class ? If mySpecialMethod() takes a Class as parameter, then it makes no sense instantiating an array. –  bali182 12 hours ago
    
the method expects 'Class<? extends MySpecialClass[]> c' as param –  user3280180 12 hours ago
    
I see, my bad . –  bali182 12 hours ago

1 Answer 1

up vote 15 down vote accepted

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

example.mySpecialMethod(MySpecialClass[].class)
share|improve this answer
    
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 12 hours ago
    
@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 12 hours ago
    
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 12 hours ago
1  
@biziclop: Your question was already answered: Obtaining the array Class of a component type. –  Jean Hominal 10 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.