【问题标题】:Non-static method of a different class cannot be referenced from a static context [duplicate]不能从静态上下文中引用不同类的非静态方法[重复]
【发布时间】:2023-03-15 14:52:01
【问题描述】:

我有一个名为AttachmentsBean 的类,它有一个名为showUploadDialog() 的方法。在另一个名为UploadBean 的类中,当我执行以下代码时:

if(count=0)
{
   return AttachmentsBean.showUploadDialog();
}   

我得到错误:

“不能从静态上下文中引用非静态方法”。

请提出建议。

【问题讨论】:

    标签: java static-methods


    【解决方案1】:

    AttachmentsBean.showUploadDialog() 仅在使用 static 修饰符声明 showUploadDialog 时才适用。

    【讨论】:

      【解决方案2】:

      showUploadDialog() 的签名应该是这样的

      public static <return type> showUploadDialog() {
       //Do something
      }
      

      【讨论】:

        【解决方案3】:

        只有当 showUploadDialog 声明为静态时,才能使用 AttachmentsBean.showUploadDialog():

        public static ... showUploadDialog() {
          ...
        }
        

        如果需要调用非静态方法,首先需要创建AttachmentsBean对象,例如:

        if(count=0)
        {
           return new AttachmentsBean().showUploadDialog();
        }   
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-31
          • 2023-03-22
          • 1970-01-01
          • 2012-11-02
          • 2016-09-17
          相关资源
          最近更新 更多