I am having doubt on below code which uses parameter as java.lang.reflect.Array
.
public static void display(java.lang.reflect.Array stringArray) {
System.out.println(java.lang.reflect.Array.get(stringArray, 1));
}
Above mentioned code will compile successfully but whether i should write this method and what could be the possible use-case?
if i can write such method how can we call this method however we can not instantiate java.lang.reflect.Array
and also we can not get object from Class
class reference as we can get java.lang.reflect.Field
object.
Array
is just a helper class - note how all the methods on it are static. I wouldn't expect there to ever be an instance of it. To accept an array - and any array, including int[]
etc - you'd need to make the method accept Object
:
public static void display(Object stringArray) {
System.out.println(java.lang.reflect.Array.get(stringArray, 1));
}
At that point, you can pass a String[]
as the argument, and it will print out the second element.
However, if you want to only accept string arrays, why not write:
public static void display(String[] stringArray) {
System.out.println(stringArray[1]);
}
? Now it's clear what you intend...
See more on this question at Stackoverflow