[英]How to create a generic class in what I can call an Enum.valueOf() in Java?
所以我有这些课程:
public class DeviceInState implements MyInterface<Device> {
private List<DeviceState> toStates(String statesString) {
List<String> states = Lists.newArrayList(statesString.split(","));
return states.stream().map(DeviceState::valueOf).collect(Collectors.toList());
}
}
public class DeviceHistoryInState implements MyInterface<DeviceHistory> {
private List<EventType> toStates(String statesString) {
List<String> states = Lists.newArrayList(statesString.split(","));
return states.stream().map(EventType::valueOf).collect(Collectors.toList());
}
}
这些枚举:
public enum EventType{
NEW("N"), ACTIVE("A"), INACTIVE("I");
}
public enum DeviceState{
REGISTRATED("R"), SUSPENDED("S"), DELETED("D");
}
区别在于:
DeviceInState implements MyInterface<Device>
; 但DeviceHistoryInState implements MyInterface<DeviceHistory>
DeviceState::valueOf
在DeviceInState
被调用; 但EventTypes::valueOf
在DeviceHistoryInState
被调用
我有几个这样的其他类,所以我想制作一个通用的类。 但我不知道这是否可能。 我如何以一种可以调用::valueOf
方法的方式参数化我的类或方法?
提前致谢。
这就是我要做的……
public interface State< E extends Enum< E > > { … }
然后我的enums
会实现......
…
public enum DeviceState implements State< DeviceState > { … }
…
public enum EventType implements State< EventType > { … }
…
„ ……其实这些方法都没有被覆盖。 这些方法只是从被覆盖的方法中调用…… ”
考虑到您使用@Overrides
注释了代码段中的方法,我发现这是一个非常令人困惑的评论。 为了让我自己不那么困惑,我的实验性实现确实覆盖了一些东西......
public class DeviceInState extends ToStateable< DeviceState > implements Specification< Device > {
@Override
public List< DeviceState > toStates( String statesString ) {
List< String > states = asList( statesString.split( "," ) );
return states.stream( ).map( String::trim ).map( DeviceState::valueOf ).collect(Collectors.toList());
}
}
我能够成功地称之为......
…
ToStateable< DeviceState > deviceToStateable = new DeviceInState( );
List< DeviceState > deviceStates = deviceToStateable.toStates( "SUSPENDED,REGISTERED,DELETED" );
ToStateable< EventType > eventToStateable = new DeviceHistoryInState( );
List< EventType > eventTypes = eventToStateable.toStates( "INACTIVE, NEW, ACTIVE" );
…
打印出我能看到的那些物体……
[SUSPENDED, REGISTERED, DELETED]
[INACTIVE, NEW, ACTIVE]
SUSPENDED
EXPERIMENT SUCCESSFUL
您可以在 DeviceHistoryInState 和 DeviceInState 中删除两个类似的toState()
实现,并定义一个适用于任何枚举类型的通用方法:
static <E extends Enum<E>> List<E> toStates(Class<E> cls, String statesString) {
List<String> states = Arrays.asList(statesString.split(","));
return states.stream().map(String::trim).map(s -> Enum.valueOf(cls, s))
.collect(Collectors.toList());
}
但是有一个小成本:您必须将 EnumType.class 作为参数传递,但这相当简单:
List< DeviceState > devStates = toStates(DeviceState.class, "SUSPENDED,REGISTRATED,DELETED");
=> [SUSPENDED, REGISTRATED, DELETED]
List< EventType > evTypes = toStates(EventType.class, "INACTIVE,NEW,ACTIVE");
=> [INACTIVE, NEW, ACTIVE]
或者,您可以对调用上述内容的 EventType.toState(String) 进行简单定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.