1Z10
1Z10

Reputation: 3361

Java reflection: how to get the class of a method's generic type?

I'm trying to code a generic method, whic given just the Type as input is able to access the corresponding class. Note that no parameter is passed to the method (as already answered here), but just the type is specified.

Here is the corresponding code:

@Bean
public <T> ConsumerFactory <String, T> consumerFactory() {
 Class <T> genericClass = null; //How to get the class corresponding to type T ? 

 return new DefaultKafkaConsumerFactory<>(consumerConfigs(),
  new StringDeserializer(),
  new JsonDeserializer<>(genericClass, objectMapper)
 );
}

Upvotes: 1

Views: 88

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44980

You probably should introduce a type token as a method parameter. You won't be able get T information as it's erased during compilation.

@Bean
public ConsumerFactory<String, String> newStringConsumerFactory() {
  return newConsumerFactory(String.class);
}

private <T> ConsumerFactory <String, T> newConsumerFactory(Class<T> t) {
 return new DefaultKafkaConsumerFactory<>(consumerConfigs(),
  new StringDeserializer(),
  new JsonDeserializer<>(t, objectMapper)
 );
}

You could try digging into reflection and Method.getGenericParameterTypes() but it doesn't make the @Configuration readable. The verbosity and adhering to standards here is important as most IDEs are supporting Spring config and auto-wire hints

Upvotes: 2

Related Questions