【问题标题】:Why I get error "non-static variable this cannot be referenced from a static context"?为什么我收到错误“无法从静态上下文引用的非静态变量”?
【发布时间】:2012-08-14 16:38:35
【问题描述】:

我已经阅读了有关 non-static variable this cannot be referenced from a static context 错误的信息,但我不明白为什么会在我的情况下得到它(return new CommandParser1(command); 行)?我只是创建类的实例。就这样。有什么问题?

public class ProtocolUtility {

    public static CommandParser createParser(String command) throws Exception {           
        switch (command) {
            case COMMAND_1:
                return new CommandParser1(command);                  
            case COMMAND_2:
               return new CommandParser2(command);
            default:
                return null;
        }
    }

   public abstract class CommandParser {

       protected String command;

       public String getCommand() {
          return command;
       }       
   }

   public  class CommandParser1 extends CommandParser {       
       public CommandParser1 (String command){
           //...
       }       
   }

   public  class CommandParser2 extends CommandParser {      
       public CommandParser2 (String command)  {
           //...
       }      
   }

}

【问题讨论】:

标签: java static inner-classes


【解决方案1】:

CommandParser 是一个内部类,这意味着它需要创建外部类 (ProtocolUtility) 的实例。将其声明更改为:

public static abstract class CommandParser {

或者在单独的.java 文件中声明CommandParser

如果createParser() 不是static,您的代码也可以工作,因为在这种情况下,您当前所在的ProtocolUtility 实例将用作外部实例。

【讨论】:

    【解决方案2】:

    createParser 以静态方式调用(即ProtocolUtility.createParser(...))时,您不能从ProtocolUtility 中定义的类实例化对象,因为这需要您拥有该类的实例(您没有)。这也可以通过使内部类static 来解决。

    【讨论】:

      【解决方案3】:

      因为 CommandParser1() 不是静态的。您需要一个 CommandParser1 实例来调用 CommandParser1() 或将其定义为静态。

      【讨论】:

        【解决方案4】:

        1. Static method 无法访问 Non-static method or variable.

        你的代码return new CommandParser1(command);内部静态方法 public static CommandParser createParser(String command),所以这是导致错误的原因。

        2. 当您尝试从class ProtocolUtility 访问CommandParser1(command) inner class 这是它的 outer class你现在可以直接访问它 但是假设,当您尝试从外部访问它ProtocolUtility class,那么您需要创建一个外部类实例来访问这个内部类方法。

        【讨论】:

        • 请不要介意使用大写和粗体的错误。重要的是内容;评论者根据我的估计正确解释了这个问题。
        • @Mark Rotteveel 如果外观对您来说比答案的技术正确性更重要,最好加入一些管理领域。
        猜你喜欢
        • 2012-05-05
        • 1970-01-01
        • 2010-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-25
        • 1970-01-01
        相关资源
        最近更新 更多