[英]Java wildcard return type for abstract method
The Java documentation for wildcards says that they can be used as return types but it is generally not a good idea. 用于通配符的Java文档说,可以将它们用作返回类型,但这通常不是一个好主意。 Is this still true if the wildcard is used as the return type for an abstract method but the class that implements this method returns a concrete type?
如果将通配符用作抽象方法的返回类型,但实现此方法的类返回具体类型,这是否仍然正确? If not, what is the best way to handle this type of situation.
如果没有,那么处理这种情况的最佳方法是什么。 Consider the example below.
考虑下面的示例。 In this case,
Entity
might be modeled after a JSON REST response, where in the second case the result is just a list of Strings. 在这种情况下,可以在JSON REST响应之后对
Entity
进行建模,在第二种情况下,结果只是一个字符串列表。 Is it better to use List<Object>
as the return type or something else entirely? 最好使用
List<Object>
作为返回类型还是完全使用其他类型?
public abstract class AbstractClient {
public abstract List<?> listEntities();
}
public class ConcreteClient {
@Override
public List<Entity> listEntities();
}
public class ConcreteClient2 {
@Override
public List<String> listEntities();
}
In such a case it is better to use generics properly instead of using wildcards. 在这种情况下,最好正确使用泛型而不是使用通配符。 Use a type parameter and extend the abstract class with the appropriate argument for the type parameter:
使用类型参数,并使用类型参数的适当参数扩展抽象类:
public abstract class AbstractClient<T> {
public abstract List<T> listEntities();
}
public class ConcreteClient extends AbstractClient<Entity> {
@Override
public List<Entity> listEntities();
}
public class ConcreteClient2 extends AbstractClient<String> {
@Override
public List<String> listEntities();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.