java中如何传递泛型类类型
我有一个名为的预定义类
ParameterList<Recipient_Type,Subject_Type> {
//some code here...
}
,它是采用收件人类型和主题类型的通用类。我有一个称为通信的对象,它有用于设置不同类型主题的设置方法,例如
correspondence.setSubject1((Subject1)subject)
correspondence.setSubject2((Subject2)subject).
以及用于设置不同类型收件人的类似方法,
correspondence.setRecipient1((Recipient1)recipient),
correspondence.setRecipient2((Recipient2)recipient),
correspondence.setRecipient3((Recipeint3)recipient).
所以基本上我有 2 种不同的主题类型和 3 种不同类型的收件人。直到这部分代码我无法更改任何内容,因为它是一些现有的框架代码。
现在我有一个以下方法,它将我的通信对象作为参数,并且需要实例化 ParameterList 类,传递正确的主题和收件人类型。通信对象上只会设置一个主题和收件人。所以在下面的方法中
public void doTheJob(Correspondence correspondence){
//How do I instantiate the ParameterList class provided subject can be any one of the two
//and recipient can be any one of the three.
}
I have a pre-defined class called
ParameterList<Recipient_Type,Subject_Type> {
//some code here...
}
which is generic to take recipient type and subject type. I have an object called correspondence which has got setter methods for setting different kind of subjects like
correspondence.setSubject1((Subject1)subject)
correspondence.setSubject2((Subject2)subject).
And similar methods for setting different kind of recipients like
correspondence.setRecipient1((Recipient1)recipient),
correspondence.setRecipient2((Recipient2)recipient),
correspondence.setRecipient3((Recipeint3)recipient).
So basically I have 2 different subject types and 3 different kind of recipients. Till this part of code I can not change anything because its some existing framework code.
Now I have a following method which takes my correspondence object as a parameter and need to instantiate ParameterList class passing the correct subject and recipient type. There will be only one subject and recipient set on correspondence object. So in the below method
public void doTheJob(Correspondence correspondence){
//How do I instantiate the ParameterList class provided subject can be any one of the two
//and recipient can be any one of the three.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法在运行时决定泛型类型,因为泛型主要在编译时使用。因此,如果您不知道确切的类型参数,请使用
?
You can't decide the generic type at runtime, because generics are used mainly at compile time. So in case you don't know the exact type parameter, use
?
您可以:
?
,正如 Bozho 所说?扩展 WrapperBean
SubjectN
类继承公共超类型,并且所有RecipientN
类继承公共超类型You can either:
?
, as Bozho has said? extends WrapperBean
SubjectN
classes inherit a common supertype and allRecipientN
classes inherit a common supertype