java中如何传递泛型类类型

发布于 2024-12-08 05:24:19 字数 904 浏览 0 评论 0原文

我有一个名为的预定义类

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

感情洁癖 2024-12-15 05:24:19

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

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 ?

绝不服输 2024-12-15 05:24:19

您可以:

  • 使用 ?,正如 Bozho 所说
  • 使用(稍微)更具体的 ?扩展 WrapperBean
  • 重构(如果可能),以便所有 SubjectN 类继承公共超类型,并且所有 RecipientN 类继承公共超类型

You can either:

  • Use ?, as Bozho has said
  • Use the (slightly) more specific ? extends WrapperBean
  • Refactor (if possible) so that all SubjectN classes inherit a common supertype and all RecipientN classes inherit a common supertype
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文