Uro*_*nym 4 java static exception inner-classes
这个错误意味着什么,为什么适用?在一个与我的情况相关的案例中,我无法找到关于成员类和静态上下文的内容,或者那些含义的内容.
这是我得到的错误:
non-static variable this cannot be referenced from a static context
它指向这一行,并指向new运营商:
throw new ParenthesisException();
ParenthesisException是主类的私有成员类.我认为问题可能与此有关,但这就是我所能想到的.
这是我对ParenthesisException的定义.它在主类定义中:(如果格式不是很好,我很抱歉)
private class ParenthesisException extends Throwable
{
public ParenthesisException(){}
public String strErrMsg()
{
return "ERROR: Every '(' needs a matching ')'";
}
}
Run Code Online (Sandbox Code Playgroud)
我发现错误信息相当神秘.我将非常感谢"静态上下文"的简要说明,以及为什么new运算符不适用于我的成员类,以及如何抛出私有成员类的实例.
如果我必须根据您发布的代码片段猜测发生了什么,可能是因为您试图抛出ParenthesisException一个static方法而导致错误.
在Java中,在另一个类中定义的类自动存储指向创建它们的对象的指针.它ParenthesisException有一个隐式指针,指向它所创建的封闭类new.这意味着,特别是,您无法构造方法的new ParenthesisException内部static,因为没有this可用于引用包含类的指针.
要解决这个问题,你应该创建ParenthesisException一个这样的static内部类:
private static class ParenthesisException extends Throwable
{
public ParenthesisException(){}
public String strErrMsg()
{
return "ERROR: Every '(' needs a matching ')'";
}
}
Run Code Online (Sandbox Code Playgroud)
这static之后private说ParenthesisException没有引用回到一个封闭的对象,这可能是你想要的.它还意味着您可以new ParenthesisException在静态方法中创建s.
希望这个猜测是正确的,希望这有帮助!