gpt4 book ai didi

Java,子类返回泛型的泛型

转载 作者:行者123 更新时间:2023-12-01 18:46:13 25 4
gpt4 key购买 nike


有谁能告诉我如何在函数“getDirectHair()”中编写返回代码吗?
我想创建一个类似于 Human 类中的快捷方式的方法,直接返回 Hair 类的良好类型(下面名为“h.getDirectHair()”),而不是使用“h.getPerson().getHair()”。
我想使用 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 {
}


非常感谢和最诚挚的问候,
大卫。

最佳答案

解决该问题的方法如下:

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();
}
}

关于Java,子类返回泛型的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17697855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com