繁体   English   中英

如何在Java中传递通用类类型

[英]How to pass the generic class type in 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.
}

您无法在运行时决定泛型类型,因为泛型主要在编译时使用。 因此,如果您不知道确切的类型参数,请使用?

您可以:

  • 使用? 正如博zh所说
  • 使用(略)更具体? extends WrapperBean ? extends WrapperBean
  • 重构(如果可能的话),以便所有SubjectN类都继承一个公共超类型,而所有RecipientN类都继承一个公共超类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM