How to concatenate static final String arrays in one Java statement
C宏可以很容易地解决我的问题…但是,Java似乎需要代码来实现声明由编译器静态组装的子数组的效果。其目的是能够定义一个全局数组/字符串列表,这些字符串可以在大量类中重用。
使用(邪恶)宏构造
全局.c源文件
1 | #define GLOBAL_HTML_ATTRIBUTES"accesskey","class","contenteditable","contextmenu","dir","draggable","dropzone","hidden","id","lang","spellcheck","style","tabindex","title","translate" |
A.C源文件
1 2 3 | #define A_ELEMENT_ATTRIBUTES"download","href","hreflang","media","name","rel","target","type" char[] attributes = {GLOBAL_HTML_ATTRIBUTES, A_ELEMENT_ATTRIBUTES}; |
号
有类似的Java构造吗?
是的,我知道其他一些关于串接字符串数组的问题…这个问题旨在帮助C开发人员适应Java编程习语。
您可以这样使用流:
1 2 3 4 5 6 7 8 9 10 11 12 13 | static final String[] GLOBAL_HTML_ATTRIBUTES = { "accesskey","class","contenteditable","contextmenu", "dir","draggable","dropzone","hidden","id","lang", "spellcheck","style","tabindex","title","translate"}; static final String[] A_ELEMENT_ATTRIBUTES = { "download","href","hreflang","media","name","rel", "target","type"}; static final String[] attributes = Stream.concat( Stream.of(GLOBAL_HTML_ATTRIBUTES), Stream.of(A_ELEMENT_ATTRIBUTES)) .collect(Collectors.toList()).toArray(new String[]{}); |
使用@realconsoluter提供的洞察力,我重构如下:
用"global"字符串抽象"base"类
1 2 3 4 5 6 7 8 9 | public class Abstract_Html_Element { protected static final List<String> attributes = new ArrayList<String>(Arrays.asList("accesskey","class","contenteditable","contextmenu","dir","draggable","dropzone","hidden","id","lang","spellcheck","style","tabindex","title","translate")); public Abstract_Html_Element() { super(); } } |
。
具有静态初始化块的子类
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class A_Element extends Abstract_Html_Element { public static final List<String> attributes = new ArrayList<String>(Arrays.asList("download","href","hreflang","media","name","rel","target","type")); { A_Element.attributes.addAll(Abstract_Html_Element.attributes); } public A_Element() { super(); } } |
这很干净,很容易理解…并且每次执行时只初始化每个列表一次…(最佳实践?)
这是我觉得美学上令人满意的方法(在一个未成型的C开发人员的眼中,从后面看):
定义"全局"字符串所在的基类(如下所示)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class Abstract_Html_Element { private static final List<String> attributes = new ArrayList<String>(Arrays.asList("accesskey","class","contenteditable","contextmenu","dir","draggable","dropzone","hidden","id","lang","spellcheck","style","tabindex","title","translate")); public Abstract_Html_Element(final List<String> attributes) { super(); if (null != attributes) { Abstract_Html_Element.attributes.addAll(attributes); } } } |
号
然后在实现子类中传递要连接的字符串的数组列表(如下所示):
1 2 3 4 5 6 7 8 9 | public class A_Element extends Abstract_Html_Element { public static final List<String> attributes = new ArrayList<String>(Arrays.asList("download","href","hreflang","media","name","rel","target","type")); public A_Element() { super(attributes); } } |
奇怪的是,通过传递的属性可以很高兴地连接到私有的最终列表属性,这些属性不是在类的实例中引用的,而是在抽象类本身中引用的-这向我暗示了我想要达到的效果,即在子类…我不知道如何检验我的假设…但是,如果编译器真的能够以"单例"的方式附加字符串数组,那么学习它是很有趣的…