Java 从静态外部util函数访问内部类
我的班级结构大致如下:Java 从静态外部util函数访问内部类,java,static,Java,Static,我的班级结构大致如下: final public class Util { private Util() { throw new AssertionError(); // there is not supposed to exist an instance } public static DataElem getData() { return new Util().new DataElem(); } public cla
final public class Util {
private Util() {
throw new AssertionError(); // there is not supposed to exist an instance
}
public static DataElem getData() {
return new Util().new DataElem();
}
public class DataElem {
// class definition
}
}
正确生成内部类实例的代码取自thread。但我不喜欢每次生成内部类实例时,都首先生成外部类的实例。由于我将AssertionError放入了它的构造函数中,所以它不起作用
我是否必须携带一个虚拟实例来从内部类创建实例?我不能让Util.DataElem这样的东西工作吗?您可以使内部类保持静态
final public class Util {
private Util() {
throw new AssertionError(); // there is not supposed to exist an instance
}
public static DataElem getData() {
return new Util.DataElem();
}
private static class DataElem {
private DataElem(){} // keep private if you just want elements to be created via Factory method
// class definition
}
}
然后像这样初始化它
new Util.DataElem();
将
static
添加到DataElem
的类头中?这个return new DateElem()
@Braj怎么样?你应该删除return=new Util().new DataElem()中的=
。只需返回new datelem()
就不需要添加Util
类名,因为它已经在Util
类中。@JigarJoshi。。。不,不是。=
仍然是一个错误。