简体   繁体   中英

Java Reflection, extract generic type from method

I have a java method with the following signature:

static <ContentType> Map<Object,ContentType> foo();

I want to use reflection to dynamically change the behavior of the method according to ContentType . To achieve this, I must be able to handle ContentType as an object (maybe an instance of java.lang.reflect.Type). Does anyone know how to do this? Is that event possible?

It's not possible. Generics in Java are "syntactic sugar". They are only used at compile-time but are then removed and never make it into the class file.

This question has some realy good information on this.

At runtime inspecting a parameterizable type itself, like java.util.List, there is no way of knowing what type is has been parameterized to. But, when you inspect the method that declares the use of a parameterized type, you can see at runtime what type the parameterizable type was parameterized to

Method method = MyClass.class.getMethod("getStringList", null);

Type returnType = method.getGenericReturnType();
if(returnType instanceof ParameterizedType){
  ParameterizedType type = (ParameterizedType) returnType;
  Type[] typeArguments = type.getActualTypeArguments();
  for(Type typeArgument : typeArguments){
      Class typeArgClass = (Class) typeArgument;
      System.out.println("typeArgClass = " + typeArgClass);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM