2

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?

edhoedt
  • 23
  • 2

2 Answers2

2

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.

Community
  • 1
  • 1
Phil Anderson
  • 3,046
  • 11
  • 23
  • Note : It will probably be possible from Java 9. – Arnaud Denoyelle Jun 02 '15 at 08:08
  • @ArnaudDenoyelle Why do you say it will be possible in Java 9? If you're talking about the generic changes included as part of the [value types proposal](http://openjdk.java.net/jeps/169), that is currently targeted for Java 10 (and is very far from completion, so this might not end up being possible). –  Jun 02 '15 at 08:11
  • @PhilAnderson It is called `reification` and as says Toby, it is not clear whether it will be ready for Java 9 or Java 10. https://blogs.oracle.com/java/entry/the_javaone_2013_technical_keynote – Arnaud Denoyelle Jun 02 '15 at 08:13
  • @ArnaudDenoyelle From my understanding full reification is no longer a goal ([JEP 218: Generics over Primitive Types](https://bugs.openjdk.java.net/browse/JDK-8046267)), although this could of course change. –  Jun 02 '15 at 08:16
1

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);
  }
}
Arjit
  • 2,972
  • 1
  • 15
  • 16