开发者

How to pass the generic class type in java

开发者 https://www.devze.com 2023-04-10 02:32 出处:网络
I have a pre-defined class called ParameterList<Recipient_Type,Subject_Type> { //some code here...

I have a pre-defined class called

ParameterList<Recipient_Type,Subject_Type> {
//some code here...
}

which is generic to take recipient type and subje开发者_开发百科ct 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.
}


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
  • 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
0

精彩评论

暂无评论...
验证码 换一张
取 消