Java - 限制返回类似T <s>的泛型的方法

时间:2018-03-11 10:10:45

标签: java generics types syntax

java中有没有办法限制方法像这段代码一样返回T<S>

public <T extends MyOwnCls1, S extends MyOwnCls2> T<S> func(Class<T> c1, Class<S>... c2) {
  ...
}

<S>中的T<S>存在问题。

2 个答案:

答案 0 :(得分:3)

仅当if(FILE* fp = std::fopen(soubor, "rb")) { char buf[1024]; std::size_t bytesrx; while((bytesrx = std::fread(0, 1, sizeof(buf), fp)) > 0) { int bytestx; if((bytestx = send(client_socket, buf, bytesrx, 0) < 0)) { // socket error std::cout << "socket error: " << std::strerror(errno) << '\n'; return EXIT_FAILURE; } } if(bytesrx < 0) { // file error std::cout << "file error: " << std::strerror(errno) << '\n'; return EXIT_FAILURE; } } else { // error opening file } 具有泛型类型时才可以这样做:

MyOwnCls1

答案 1 :(得分:1)

协方差适用于基类型,因此您应该能够在MyOwnCls1上没有有界参数的情况下编写它:

public <S extends MyOwnCls2> 
       MyOwnCls1<S> func(Class<? extends MyOwnCls1> p1, Class<S>... p2) {

}
//Kept p1 just as I suppose you need it in code.

你应该能够使用MyOwnCls1的子类型

MyOwnSubCls1<MyOwnSubCls2> res = func(MyOwnSubCls1.class, MyOwnSubCls2.class);

参数Class<? extends MyOwnCls1> p1只适用于您的方法,不应导致您的泛型类型无效,除非您的方法实现需要MyOwnCls1MyOwnCls2之间的不同链接