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?

3
  • it will not be possible before java 9 because of type erasure. Commented Jun 2, 2015 at 8:08
  • The only way to do this is by adding an argument: static <ContentType> Map<Object,ContentType> foo(Class<ContentType> type); Commented Jun 2, 2015 at 8:17
  • or, of course, testing the content of the map. Commented Jun 2, 2015 at 8:21

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Note : It will probably be possible from Java 9.
@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, that is currently targeted for Java 10 (and is very far from completion, so this might not end up being possible).
@PhilAnderson It is called reification and as says Toby, it is not clear whether it will be ready for Java 9 or Java 10. blogs.oracle.com/java/entry/the_javaone_2013_technical_keynote
@ArnaudDenoyelle From my understanding full reification is no longer a goal (JEP 218: Generics over Primitive Types), although this could of course change.
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);
  }
}

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.