英文:
How to create a Enum with a abstract method that returns a generic type that can be a Functional Interface like functions, consumers, suppliers
问题
以下是翻译好的部分:
我有一个枚举,其中有一个字段```value```和一个抽象方法,该方法返回一个可以是函数接口的泛型类型,以便每个常量都具有特定的行为。
public enum TestEnum {
PERIOD("PERIOD") {
@Override
public <T> T operation() {
return () -> Map.of(
"INIT", LocalDate.now()
.minusDays(1L)
.with(TemporalAdjusters.firstDayOfMonth())
.minusMonths(1L),
"END", LocalDate.now()
.minusDays(1L)
.minusMonths(1L)
.with(TemporalAdjusters.lastDayOfMonth())
);
}
};
private final String value;
public abstract <T> T operation();
}
在这种情况下,可以返回一个供应商,但我有其他情况可能需要返回Function和BiConsumers。
这样做时,我收到一个需要类型T但我提供了一个lambda表达式的错误。是否有方法可以做到这一点?
英文:
I have a Enum that have a field value and a abstract method that returns a generic type that can be a functional interface to each constant will have your particular behavior.
public enum TestEnum {
PERIOD("PERIOD") {
@Override
public <T> T operation() {
return () -> Map.of(
"INIT", LocalDate.now()
.minusDays(1L)
.with(TemporalAdjusters.firstDayOfMonth())
.minusMonths(1L),
"END", LocalDate.now()
.minusDays(1L)
.minusMonths(1L)
.with(TemporalAdjusters.lastDayOfMonth())
);
}
};
private final String value;
public abstract <T> T operation();
}
In this can return a supplier but I have other scenarios that can return a Function, and BiConsumers.
Doing this I'm receiving a error that required type T but I'm providing a lambda expression.
Is there a way to do that?
答案1
得分: 1
使用一般的 Function 可能允许您声明其他任意操作:
public enum TestEnum {
PERIOD("PERIOD") {
@Override
public Function<Void, Map<String, LocalDate>> operation() {
return xxxNotUsed -> Map.of(
"INIT", LocalDate.now()
.minusDays(1L)
.with(TemporalAdjusters.firstDayOfMonth())
.minusMonths(1L),
"END", LocalDate.now()
.minusDays(1L)
.minusMonths(1L)
.with(TemporalAdjusters.lastDayOfMonth())
);
}
};
TestEnum(String x) { value = x;}
private final String value;
public abstract <T,R> Function<T, R> operation();
}
请注意,我已经使用 Void 作为 PERIOD 所需的 "Supplier" 风格调用的虚拟参数类型,并且您可以使用 Function<XYZClass, Void> 作为 "Consumer" 风格的操作。
英文:
A version using a general Function might allow you to declare other arbitrary operations:
public enum TestEnum {
PERIOD("PERIOD") {
@Override
public Function<Void,Map<String,LocalDate>> operation() {
return xxxNotUsed -> Map.of(
"INIT", LocalDate.now()
.minusDays(1L)
.with(TemporalAdjusters.firstDayOfMonth())
.minusMonths(1L),
"END", LocalDate.now()
.minusDays(1L)
.minusMonths(1L)
.with(TemporalAdjusters.lastDayOfMonth())
);
}
};
TestEnum(String x) { value = x;}
private final String value;
public abstract <T,R> Function<T,R> operation();
}
Note that I've used Void as a dummy parameter type for the "Supplier" style of call you wanted for PERIOD, and you could use Function<XYZClass,Void> for "Consumer" style of operation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论