Java格式字符串的语法可能会变得复杂,例如:
"|%1$-10s|%2$-10s|%3$-20s|\n"
有人创建一个流畅的DSL来帮助构建这些格式字符串似乎已经成熟(类似于Jooq对sql的作用).
这样的事情存在吗?
解决方法
您可以使用
fluflu
(一种流畅的API生成器)创建这样的API,其灵感来自
jOOQ’s API和
jOOQ’s underlying API design techniques.
Fluflu提供使用APT工具处理的注释,以从API实现生成流畅的API.注释模拟有限状态机.这是他们的维基的一个例子:
@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,1}); d.end(); e.end();
当然,您仍然需要编写实现:-)