【发布时间】:2013-08-04 22:40:25
【问题描述】:
这有点难以解释,但我到处寻找,找不到任何好的答案。
我也看过 Stack Overflow 问题 How can I refer to the class type a interface is implementing in Java? 和 How do I return an instance of an object of the same type as the class passed in using Java 6?,但他们无法回答我的问题。应用继承时出现异常。
有一个例子,方便理解:
假设我有一个名为 SelfMaker 的界面:
public interface SelfMaker <SELF>{
public SELF getSelf();
}
A 有一条狗,它可以和其他狗一起生育。所以狗是一个“自我创造者”,像这样:
public class Dog implements SelfMaker<Dog> {
String color;
public String toString() {
return "some " + color + " dog";
}
public Dog procreate(Dog anotherDog) {
Dog son = getSelf();
son.color = color;
return son;
}
@Override
public Dog getSelf() {
return new Dog();
}
}
但是,我有一只家养狗,它是一只狗,但它有一个可爱的家庭给他取名。像这样:
public class DomesticDog extends Dog {
private String name;
public String toString() {
return super.toString() + " named " + name;
}
}
现在,我有一些类可以处理一些“SelfMaker”的事情,我们称这个类为“Couple”。像这样:
public class Couple<T extends SelfMaker<T>> {
private T first;
private T second;
public String toString() {
return first.toString() + " and " + second.toString();
}
}
例外:
当我想创建几个DomesticDogs 时出现异常。像这样:
public class CoupleOfDomesticDogs extends Couple<DomesticDog>{
public DomesticDog procreate(){
DomesticDog son = first.procreate(second);
return son;
}
}
这将在 <DomesticDog> 抱怨时引发异常:Bound mismatch: The type DomesticDog is not a valid substitute for the bounded parameter <T extends SelfMaker<T>> of the type Couple<T>
我已经尝试将类 Couple 的广义变量更改为:Couple<T extends SelfMaker<?>>,但“儿子”不会是 DomesticDog(我希望“儿子”成为 DomesticDog)。如果我添加一些演员表,那么它会编译,但它会不太清晰。
所以...这里的问题是:有没有一种方法可以在没有强制转换和概括的情况下实现这一目标?
【问题讨论】:
-
当前类的Class是this.getClass()。类名是 this.getClass().getName()。这是最好的。并且没有办法在 Java 中动态指定强制类型转换。