How to specific a Java Generic class dynamicly

2019-03-01 03:09发布

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 =Class.forName(keytype);
        Class d= Class.forName(valuetype);
        KafkaConsumer<c,d> consumerconsumer = new KafkaConsumer<c,d>(PropertiesUtil.getPropsObj(configPath));
        return consumer ;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }


}

But the code above is not OK. How can I do than I can achieve that?

2条回答
▲ chillily
2楼-- · 2019-03-01 03:54

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.

查看更多
Deceive 欺骗
3楼-- · 2019-03-01 03:55

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

查看更多
登录 后发表回答