简体   繁体   English

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

[英]How to pass the generic class type in java

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. 所以基本上我有2种不同的主题类型和3种不同的收件人。 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. 现在,我有一个以下方法,该方法将我的对应对象作为参数,并且需要实例化传递正确主题和收件人类型的ParameterList类。 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.
}

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 ? 因此,如果您不知道确切的类型参数,请使用?

You can either: 您可以:

  • Use ? 使用? , as Bozho has said 正如博zh所说
  • Use the (slightly) more specific ? extends WrapperBean 使用(略)更具体? extends WrapperBean ? extends WrapperBean
  • Refactor (if possible) so that all SubjectN classes inherit a common supertype and all RecipientN classes inherit a common supertype 重构(如果可能的话),以便所有SubjectN类都继承一个公共超类型,而所有RecipientN类都继承一个公共超类型

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

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