我想创建一个方法,它通过它的值返回枚举常量。
我有多个枚举类,它们看起来像这样(其中一些具有不同名称的 getter 变量):
@AllArgsConstructor
public enum PhoneType {
MOBILE("Mobile", 3),
HOME("Home", 6),
WORK("Work", 7);
@Getter
String type;
@Getter
int id;
}
Run Code Online (Sandbox Code Playgroud)
我使用这个流来获取枚举常量:
int phoneTypeId = 3;
PhoneType phoneType = Arrays.stream(PhoneType.values())
.filter(p -> p.getId() == phoneTypeId)
.findFirst()
.orElseThrow(() -> new RuntimeException("Not able to find Enum...."));
System.out.println(phoneType.getType());
Run Code Online (Sandbox Code Playgroud)
输出为:“移动”
现在我想创建一个适用于不同枚举类的方法。我从这样的事情开始,但我不知道如何重写过滤器行,使其适用于任何枚举类。最好将此“p -> p.getId() == phoneTypeId”作为输入参数传递给此方法。有任何想法吗?
public static <E extends Enum<?>> E getEnumByValue(Class<E> enumClass) {
return Arrays.stream(enumClass.getEnumConstants())
.filter(p -> p.getId() == phoneTypeId)
.findFirst()
.orElseThrow(() -> new RuntimeException("Not able to find Enum...."));
} …Run Code Online (Sandbox Code Playgroud) 我有这样存储的特定操作的 UTC 时间偏移:(这是 UTC+2)
double utc = 2.0;
Run Code Online (Sandbox Code Playgroud)
如何在 Java 中使用此双时间偏移量获取该时区的当前时间?