How to specific a Java Generic class dynamicly

后端 未结 2 1243
青春惊慌失措
青春惊慌失措 2021-01-23 06:11

If I specific a method which return a generic class,how can I do than I can specific the type of generic class dynamicly ? for example

  try {
        Class c =C         


        
2条回答
  •  我在风中等你
    2021-01-23 06:40

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

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

    or

    KafkaConsumer consumerconsumer1 = (KafkaConsumer) new KafkaConsumer(PropertiesUtil.getPropsObj(configPath));
    

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

提交回复
热议问题