0

I am trying to write this function:

public static Class arrayTypeFor(Class elementType)
{
     // ... implementation ???
}

Usage:

arrayTypeFor(int.class); // this should return a Class which is equal to int[].class

How do I do this?

I thought about doing this (but it looks pretty inefficient to me).

Array.newInstance(elementCType, 1).getClass();
One Two Three
  • 22,327
  • 24
  • 73
  • 114
  • I think you're looking for [Java Generics](http://docs.oracle.com/javase/tutorial/java/generics/why.html) – Salah Apr 16 '14 at 14:29
  • Maybe this will be useful for you? Your are possibly interested in Class.forName(className) method http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html. Something like Class.forName(elementType.class.getName() + "[]"); – tmn4jq Apr 16 '14 at 14:30
  • yeah, I know these basics on Generics and stuff. But that stilldoesn't help much! – One Two Three Apr 16 '14 at 14:32
  • 1
    Why would you want something like this to begin with? Your *pretty inefficient* code works, use it until it proves it is a problem in your design. – Luiggi Mendoza Apr 16 '14 at 14:34
  • @LuiggiMendoza I don't think I need to create an entire new object just to get its class. – One Two Three Apr 16 '14 at 14:35
  • @ShibaSoft I belive you are confused between "class" and the Class object! – One Two Three Apr 16 '14 at 14:47

0 Answers0