Single dimension primitive array doesn't work correctly on generic method. new int[] should be passed as T[] instead of T. Thanks to isArray(), I'm able to differentiate an array, but having issue when try to execute Arrays.deepToString(). How to cast generic object as primitive array?
/* Output
println(T $obj)
1
println(T[] $obj)
[1]
println(T[] $obj)
[[1]]
println(T[] $obj)
[[[1]]]
println(T $obj)
1
println(T $obj)
Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
at Test.doSomething(Test.java:21)
at Test.main(Test.java:12)
Java Result: 1
*/
import java.util.Arrays;
public class Test {
public static void main(String[] args) throws Exception {
doSomething((Integer) 1);
doSomething(new Integer[]{1});
doSomething(new Integer[][]{{1}});
doSomething(new Integer[][][]{{{1}}});
doSomething((int) 1);
doSomething(new int[]{1}); //java.lang.ClassCastException
doSomething(new int[][]{{1}});
doSomething(new int[][][]{{{1}}});
}
public static <T> void doSomething(T $obj) {
System.out.println("println(T $obj)");
if ($obj.getClass().isArray()) {
System.out.println(Arrays.deepToString((T[]) $obj)); //java.lang.ClassCastException
} else {
System.out.println($obj);
}
}
public static <T> void doSomething(T[] $obj) {
System.out.println("println(T[] $obj)");
if ($obj.getClass().isArray()) {
System.out.println(Arrays.deepToString($obj));
} else {
System.out.println($obj);
}
}
}
public static <T> void doSomething(T[] $obj)or the varargs version likepublic static <T> void doSomething(T... $obj)switchonClass<T>.getComponentType()should do it.