gpt4 book ai didi

java - 接口(interface)中的静态方法不起作用,如何从多个枚举中获取特定的枚举值?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:28:08 24 4
gpt4 key购买 nike

我有几个可以通过 int 找到的枚举。这是通过枚举上的静态方法完成的。例如:

enum Foo {
A, B, C, D, ... ;
public static Foo fromInt(int i) {
switch(i) {
case 15: return A;
case 42: return B;
...
}
}
enum Bar {
BLA, BOO, BEE, ... ;
public static Bar fromInt(int i) {
switch(i) {
case 78: return BLA;
case 22: return BOO;
...
}
}
...

现在在一些代码中,我有一个泛型类型 T,它保证是这些枚举之一,我有一个整数 i。如何调用 fromInt 方法并通过值 i 获取枚举实例?

我已经尝试使用静态方法 fromInt 创建一个接口(interface)并让枚举实现它,但是静态方法在接口(interface)中不起作用。

我不能使用 Java 8。

最佳答案

简答你不能

长答案你可以将该枚举的 Class 传递给你的方法并通过反射调用 fromInt 或者创建工厂接口(interface)并为每个枚举实现它然后传递正确的实例到你的方法。

关于java - 接口(interface)中的静态方法不起作用,如何从多个枚举中获取特定的枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39208369/

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