[英]Java, Subclass return generics of generics
Does anyone can tell me how to code the return in the function "getDirectHair()" ? 有谁能告诉我如何在函数“ getDirectHair()”中对返回值进行编码?
I want to create a method which is like a shortcut in the Human class to directly return the good type of Hair class (below named "h.getDirectHair()") instead of use "h.getPerson().getHair()". 我想创建一个类似于Human类中的快捷方式的方法,以直接返回Hair类的良好类型(以下称为“ h.getDirectHair()”),而不是使用“ h.getPerson()。getHair()”。
I want to use the type <?> of Person<?> declared in Human class. 我想使用在Human类中声明的Person <?>的类型<?>。
package test;
public class Test {
public static void main(String[] args) {
Human<Bob> h = new Human<Bob>();
Blond blond = h.getPerson().getHair(); // no cast needed, because Human<Bob> is blond
//how to do if I want to use directly this :
blond = (!!!) h.getDirectHair(); //need cast !! Blond or Brown ?
}
}
class Human<T extends Person<?>>{
private T person = null;
public T getPerson() {
return person;
}
public /* <?> */ Object getDirectHair(){
// => I want to return the type <?> of Person<?>
// instead of Object, how to ??
return person.getHair();
}
}
class Person<T extends Hair> {
T hair;
public Person(T hairr) {
hair = hairr;
}
public T getHair() {
return hair;
}
}
class Bob extends Person<Blond> {
public Bob(Blond bean) {
super(bean);
}
public Blond getHair() {
return super.getHair();
}
}
class Barack extends Person<Brown> {
public Barack(Brown bean) {
super(bean);
}
public Brown getHair() {
return super.getHair();
}
}
class Hair {
}
class Blond extends Hair {
}
class Brown extends Hair {
}
Many thanks and best regards, 致以真诚的感谢和诚挚的问候,
David. 大卫。
Here's how to fix the problem: 解决问题的方法如下:
public class Test {
public static void main(String[] args) {
Human<Blond, Bob> h = new Human<Blond, Bob>();
Blond blond = h.getPerson().getHair();
blond = h.getDirectHair();
}
}
class Human<H extends Hair, T extends Person<H>>{
private T person = null;
public T getPerson() {
return person;
}
public H getDirectHair(){
return person.getHair();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.