Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance of GenericArrayType interface

class ReflectionClass{
   public static void anyMethod(Type type){
      if(type instanceof GenericArrayType){
         // some code
      }
   } 
}
class Client{
   public static void main(String[] args){
      anyMethod(...);
   }
}

I'm trying to receive a "true" value in if(type instanceof GenericArrayType) statement.

So, what I should put as an argument into invocation of anyMethod method inside Client class?

From the Oracle Documentation about GenericArrayType interface:

GenericArrayType represents an array type whose component type is either a parameterized type or a type variable.

But, I also know that I can't create arrays of parameterized types from here

Thus, how can I achieve this?

like image 753
urajah Avatar asked Sep 16 '25 01:09

urajah


1 Answers

Use reflection on any method, field, etc that's a generic array type.

For example, List.toArray(T[]) -> T[]

List.class.getMethod("toArray", Object[].class).getGenericReturnType();

Or declare a generic array yourself, and reflect on it

public List<String>[] array;

MyClass.class.getField("array").getGenericType()
like image 183
ZhongYu Avatar answered Sep 17 '25 13:09

ZhongYu