简体   繁体   中英

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. 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 ? extends WrapperBean
  • Refactor (if possible) so that all SubjectN classes inherit a common supertype and all RecipientN classes inherit a common supertype

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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