How to specific a Java Generic class dynamicly

无人久伴 提交于 2019-12-02 07:17:18

Generic syntax is good at compile-time only. None of the types in a generic class or method are available at runtime. This is called type erasure. So you cannot do what you want to do, at least not this way.

Depending on the original problem you are trying to solve, you may be able to use wildcards instead.

You can have your key and value class each implement a known interface. Then you can assign or cast it.

KafkaConsumer<IKeyType,IValueType> consumerconsumer = new KafkaConsumer<>(PropertiesUtil.getPropsObj(configPath));

or

KafkaConsumer<IKeyType,IValueType> consumerconsumer1 = (KafkaConsumer<IKeyType,IValueType>) new KafkaConsumer(PropertiesUtil.getPropsObj(configPath));

Read here about putting bounds on your generics. https://docs.oracle.com/javase/tutorial/java/generics/wildcards.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!