gpt4 book ai didi

java - 使用枚举参数化方法的返回类型——可能吗?

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

在 java 中,我知道可以例如:

static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o); // Correct
}
}

在我的场景中,我有一个不同设置的枚举,我可以为其检索一个值,其中每个设置都有不同的值类型。我想在枚举中指定这些值类型,并获得与上述类似的编译时检查。

这是一个带有运行时检查的版本——是否可以进行编译时检查?

public class Foo {
public static enum ClientSetting {
SOME_STRING_SETTING(String.class),
SOME_INTEGER_SETTING(Integer.class);

private Class valueClass;

ClientSetting(Class valueClass) {
this.valueClass = valueClass;
}
}

public static <T> T get(ClientSetting bar) {
if (bar.valueClass.equals(String.class))
return (T) "My string value.";
else if (bar.valueClass.equals(Integer.class))
return (T) new Integer(2);
else
return null; // unreachable if every possibility is checked
}

public static void main(String[] args) {
String stringValue = get(ClientSetting.SOME_STRING_SETTING);
Integer integerValue = get(ClientSetting.SOME_INTEGER_SETTING);
}
}

谢谢!

最佳答案

dacc,这样的东西对你有用吗?

public static class ClientSetting<T> {
private T setting;

ClientSetting(T setting) {
this.setting = setting;
}

public T get() {
return setting;
}
}

// Old school, I know.
public static final ClientSetting<String> SOME_STRING_SETTING =
new ClientSetting<String>("My string value.");
public static final ClientSetting<Integer> SOME_INTEGER_SETTING =
new ClientSetting<Integer>(2);

public static <T> T get(ClientSetting<T> clientSetting) {
// delegation, this method is not really needed
// you can go for SOME_STRING_SETTING.get()
return clientSetting.get();
}

public static void main(String[] args) {
String stringValue = get(SOME_STRING_SETTING);
Integer integerValue = get(SOME_INTEGER_SETTING);
// Won't compile
// String wrong = get(SOME_INTEGER_SETTING);
}

关于java - 使用枚举参数化方法的返回类型——可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5874543/

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