Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当另一类型参数为_Java_Function_Generics - Fatal编程技术网

Java 当另一类型参数为

Java 当另一类型参数为,java,function,generics,Java,Function,Generics,我试图用两个类型参数T和T1实现一个函数 如果类型参数T是类提要的实例,我希望T1是类NewFeed;如果T是类奖励的实例,我希望T1是类NewReward。所以在T和T1之间有一些固有的映射-我如何表达它 public <T> void onServerSuccessGenericList(){ ArrayList<T1> myArray = myFunction(); // this line causes problem ArrayLis

我试图用两个类型参数T和T1实现一个函数

如果类型参数T是类提要的实例,我希望T1是类NewFeed;如果T是类奖励的实例,我希望T1是类NewReward。所以在T和T1之间有一些固有的映射-我如何表达它

public <T> void onServerSuccessGenericList(){
    ArrayList<T1> myArray = myFunction();       // this line causes problem
    ArrayList<T> myArray2 = somefunction()      // hence I need T as well
}
我尝试了以下方法,但无效:

public <T> void onServerSuccessGenericList(Class t1ClsName){
    ArrayList<t1ClsName> myArray = myFunction();

}
试试这个:

public <T, T1> void onServerSuccessGenericList(Class<T> tClsName, Class<T1> t1ClsName){
    ArrayList<T1> myArray = myFunction();
    ArrayList<T> myArray2 = somefunction();
}
用法如下: onServerSuccessGenericListClsName.class、ClsName1.class; 因为ClsName.class是类类型的实例

但再一次,如果您需要使用参数化类型处理函数内部的两种不同类型,则需要将这两种类型都定义为类型参数。并将两者传递给此函数


此外,您的方法签名不正确。参数类型也应定义为泛型

您可以为提要和奖励类使用一个公共接口,该接口接受相应的NewFeed/NewReward类作为类型参数:

interface NewInterface<T>{}

class Feed implements NewInterface<NewFeed>{}
class NewFeed {}

class Reward implements NewInterface<NewReward>{}
class NewReward {}
然后,您可以这样声明您的方法:

public <T extends NewInterface<T1>, T1> void onServerSuccessGenericList(){
    ArrayList<T1> myArray = myFunction();
    ArrayList<T> myArray2 = somefunction();
}

你必须弄清楚你想做什么。签名公共无效方法毫无意义。您没有使用类型参数。可能需要两个泛型类型?我猜OP希望将T作为类型参数传递,并让他的函数使用所描述的逻辑根据T确定一个具体的类T1。在任何情况下,答案都是:ClsName.class是类类型的实例,他必须使用该实例进行操作。在这种情况下,他仍然不需要使用泛型,只需要使用两个类型的参数。这是毫无意义的使用类型参数的泛型函数,而类型参数在参数或返回中不使用。是的,目前这有点毫无意义-但这不是OP的问题。问题是,他所要求的可以通过提供一个带有类型参数的通用超级接口来设计。。。