C宏很容易解决我的问题...但似乎Java需要代码来实现声明由编译器静态组装的子数组的效果。目的是能够定义一个可以在大量类中重用的全局数组/字符串列表。
C构造使用(邪恶)宏
global.c源文件
#define GLOBAL_HTML_ATTRIBUTES "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "lang", "spellcheck", "style", "tabindex", "title", "translate"
a.c源文件
#define A_ELEMENT_ATTRIBUTES "download", "href", "hreflang", "media", "name", "rel", "target", "type"
char[] attributes = {GLOBAL_HTML_ATTRIBUTES, A_ELEMENT_ATTRIBUTES};
是否有类似的Java构造?
是的,我知道发布的其他问题是关于连接字符串数组的问题...这个问题旨在帮助很长一段时间C开发人员适应Java编程习语。
答案 0 :(得分:1)
您可以像这样使用Stream:
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[]{});
答案 1 :(得分:0)
这是我认为美学上令人愉悦的方法(对于未经过改革的C开发人员而言):
定义一个基类,其中"全局"字符串驻留(如下)
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);
}
}
}
然后在实现子类中传递一个String连接字符串(如下所示):
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);
}
}
奇特的是,传递的属性可以很好地连接到私有的最终List属性,而不是在类的实例中引用,而是在Abstract Class本身内 - 这告诉我我想要的效果实现不必在子类的每个实例化上附加两个String列表......我对如何测试我的假设没有任何线索......但是如果编译器实际设法实现了将字符串数组附加到&#34; Singleton&#34;方式...
答案 2 :(得分:0)
使用@RealSkeptic提供的洞察力,我重构如下:
摘要&#34;基地&#34;与&#34;全球&#34;字符串
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();
}
}
带有静态初始化块的子类
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();
}
}
这非常干净且易于理解......并且每次执行只会初始化每个列表...(最佳实践?)