4
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?

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.