gpt4 book ai didi

java - 如何从 Java 中的类型参数访问字段?

转载 作者:行者123 更新时间:2023-11-29 09:59:03 25 4
gpt4 key购买 nike

我有两个类 X e Y 具有相同的静态成员:

class B {
public static final String Base = "Base";
}

class X extends B {
public static final String First = "First A";
public static final String Second = "Second A";
}

class Y extends B {
public static final String First = "First B";
public static final String Second = "Second B";
}

在另一个类中,我需要一个将使用一个类或另一个类的函数:

class C {
public <Data> void f() {
System.out.println("Operation " + Data.Base);
System.out.println("Running " + Data.First);
System.out.println("Running " + Data.Second);
}
}

想法是使用C如下:

C c = new C();
if (whatever()) {
c.f<X>();
} else {
c.f<Y>();
}

但上面的代码无效,有没有办法在 Java 中实现所需的行为?

最佳答案

你需要声明非静态方法

    abstract class B {
public static final String Base = "Base";
public abstract String getFirst();
public abstract String getSecond();
}

class X extends B {
public static final String First = "First A";
public static final String Second = "Second A";

public String getFirst() { return First; }
public String getSecond() { return Second; }
}

class Y extends B {
public static final String First = "First B";
public static final String Second = "Second B";

public String getFirst() { return First; }
public String getSecond() { return Second; }
}

class C {
public void f(B b) {
System.out.println("Operation " + B.Base);
System.out.println("Running " + b.getFirst());
System.out.println("Running " + b.getSecond());
}
}

关于java - 如何从 Java 中的类型参数访问字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48419467/

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