Java 格式字符串的语法可能会变得复杂,例如:
"|%1$-10s|%2$-10s|%3$-20s|\n"
有人创建流利的 DSL 来帮助构建这些格式字符串似乎已经成熟(类似于Jooq为 SQL 所做的)。
这样的事情存在吗?
您可以使用 fluent API 生成器创建这样的 API fluflu
,它的灵感来自jOOQ 的API 和jOOQ 的底层 API 设计技术。
Fluflu 提供使用 APT 工具处理的注释,以从 API 实现生成流畅的 API。注释对有限状态机建模。以下是他们 wiki 中的一个示例:
@Fluentize(className = "CoreClass", startState = "State0", startMethod = "start")
public abstract class ToBeFluentized implements Cloneable {
@Transitions({
@Transition(from = "State0", end = true),
@Transition(from = "State1", end = true)
})
public void end() {
}
protected String with = null;
protected List<byte[]> b = new LinkedList<>();
@Transition(from = { "State0", "State1" }, to = "State0")
public abstract ToBeFluentized with(
@AssignTo("with") String a, @AddTo("b") byte[] b
);
@Transition(from = "State1", to = "State0")
public ToBeFluentized z() {
return this;
}
Set<Integer> j = new HashSet<>();
@Transition(from = "State1", to = "State1", name="a")
public abstract ToBeFluentized z(@AddTo("j") int j);
@Transition(from = "State0", to = "State1")
public ToBeFluentized a() {
return this;
}
@Transition(from = "State0", to = "State1")
public ToBeFluentized b() {
return this;
}
@Transition(from = "State0", to = "State1")
public ToBeFluentized vari(String... strings) {
return this;
}
}
然后可以这样使用:
State0 c = CoreClass.start().a().z();
State0 d = c.b().with("z", "z".getBytes());
State0 e = c.b().with("q", new byte[]{0,0,1});
d.end();
e.end();
当然,您仍然必须编写实现:-)