如何动态地指定Java泛型类 [英] How to specific a Java Generic class dynamicly

查看:1120
本文介绍了如何动态地指定Java泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我指定了一个返回泛型类的方法,那我该怎么做,而不是动态地指定泛型的类型? 例如

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?

推荐答案

您可以让您的键和值类分别实现一个已知的接口. 然后,您可以分配或投射它.

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));

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

在此处阅读有关在泛型上加界限的信息. https://docs.oracle.com/javase/tutorial/java/generics/wildcards.html

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

这篇关于如何动态地指定Java泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆