很容易定义一个返回与参数相同的值的方法:
class A {
public static void main(String[]args) {
Derived sth = new Derived();
String x = sth.foo("hello");
System.out.println(x);
Derived resultTypeIsKnown = sth.foo(sth); // <==== !!!
System.out.println(""+resultTypeIsKnown);
}
}
class Base {
<T>T foo(T t)
{
return t;
}
}
class Derived extends Base {
}
您看到编译器知道虽然在foo()
类中声明了Base
,但编译器知道sth.foo(sth)
返回Derived
类的实例:
Derived derivedRatherThanBase = sth.foo(sth);
如何声明返回值与调用其方法的对象属于同一类? (特别是对于始终返回{{ 1}}?)
类似的东西:
this
我可以写
class Base {
<?ThisClass?> bar() {
return this;
}
}
但是 <T>T getThis(T t)
{
return (T)this;
}
使用额外的参数并产生警告。
更新 OMG,他们在“可能的重复”中做了什么...但我已经有了基类,它是x.getThis(x)
的后代。换句话说,Collection
和需要知道其类别。
我想知道的真实代码class Base extends Collection
已经非常复杂了。
UPDATE2 关于XY问题,我想要的是:
THISCLASS
建议的解决方案听起来太复杂,甚至比(1)在每个派生类中重新定义addAll()或(2)使class MyVerySpecialCollectionBase extends ... {
...
THISCLASS addAll(Collection items) { ... }
}
class MyExtendedVerySpecialCollection extends MyVerySpecialCollectionBase {
...
}
// use:
MyExtendedVerySpecialCollection x =
new MyExtendedVerySpecialCollection(aLotOfArgs)
.addAll(list1)
.addAll(list2);
成为单独的语句更不可接受。