如何在java中传递泛型类类型
我有一个预定义的类叫做如何在java中传递泛型类类型,java,generics,Java,Generics,我有一个预定义的类叫做 ParameterList<Recipient_Type,Subject_Type> { //some code here... } 以及设置不同类型收件人的类似方法,如 correspondence.setRecipient1((Recipient1)recipient), correspondence.setRecipient2((Recipient2)recipient), correspondence.setRecipient3((Recipe
ParameterList<Recipient_Type,Subject_Type> {
//some code here...
}
以及设置不同类型收件人的类似方法,如
correspondence.setRecipient1((Recipient1)recipient),
correspondence.setRecipient2((Recipient2)recipient),
correspondence.setRecipient3((Recipeint3)recipient).
所以基本上我有两种不同的主题类型和三种不同的接受者。在这部分代码之前,我无法更改任何内容,因为它是一些现有的框架代码
现在我有一个方法,它将我的通信对象作为参数,需要实例化传递正确主题和收件人类型的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.
}
您不能在运行时决定泛型类型,因为泛型主要在编译时使用。因此,如果您不知道确切的类型参数,请使用?您可以: 正如波佐所说,使用 使用稍微具体一点的?扩展包装器bean 如果可能,重构,以便所有SubjectN类继承一个公共超类型,所有RecipientN类继承一个公共超类型
我更喜欢看你的代码,而不是阅读它的描述;我的问题陈述现在看起来更好了吗…Subject1将如何继承Subject\u类型?Subject1是一个类,Subject_Type是不同类的泛型类型参数。是否存在所有Subject1继承的接口或超类型?是否存在所有收件人都继承的接口或超类型?是的,Subject和Recipients都继承自名为WrapperBean的超类型。相应地更新了答案。是否将ParameterList更改为ParameterList.No。但是当你实例化use?如果我在实例化ParameterList时使用“?”,我如何传递正确类型的subject和recipient呢。在实例化时,它应该采用正确的主题和收件人类型。对的这就是全部的想法。“正确”的主题类型是什么?如果只有在运行时才知道,那么泛型就不适用于您不能使用?
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.
}