[英]Can I declare method to return Class object with restriction to subclasses of given type in Java?
Suppose I declare some abstract method, that will return Class object (like Dog.class, Cat.class), like this: 假设我声明了一些抽象方法,它将返回Class对象(如Dog.class,Cat.class),如下所示:
abstract public Class getProducedAnimalType();
Can I force clients extending this API to return only Class objects that represents classes, wchich are subclassess of Animal.class ? 我可以强制扩展此API的客户端只返回表示类的Class对象,它们是Animal.class的子类吗? something like:
就像是:
abstract public Class<representing subclass of Animal> getProducedAnimalType();
So the client extending my class cannot write: 所以扩展我的类的客户端不能写:
public Class getProducedAnimalType() {
// Integer not extends Animal!, shoud not compile!
return Integer.class;
}
but can: 但可以:
public Class getProducedAnimalType() {
return Fish.class; // Fish extends Animal
}
You can change the return type Class
to Class<? extends Animal>
您可以将返回类型
Class
更改为Class<? extends Animal>
Class<? extends Animal>
. Class<? extends Animal>
。 The following code will allow to return Cat.class
and Dog.class
, but won't allow to return Integer.class
: 以下代码将允许返回
Cat.class
和Dog.class
,但不允许返回Integer.class
:
abstract public Class<? extends Animal> getProducedAnimalType();
The client can write the following code and will compile fine: 客户端可以编写以下代码并编译正常:
public Class<? extends Animal> getProducedAnimalType()
{
return Fish.class; // Fish extends Animal
}
But the following code won't compile: 但是以下代码将无法编译:
public Class getProducedAnimalType()
{
return Integer.class;
}
public Class<? extends Animal> getProducedType() {
// return Integer.class; // compile time error: incompatible types
return Dog.class;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.