【问题标题】:Java Spring: how to call a static child method from an instance of a parent classJava Spring:如何从父类的实例调用静态子方法
【发布时间】:2022-10-08 01:27:27
【问题描述】:

我只是一个卑微的 javascript 农奴,被授予支持高级 Java 开发人员构建新后端功能的特权。

这是一个 Java Spring 后端,这里是包含我需要在控制器中访问的方法的实用程序类。

Class ParentUtil {

   public static String parentMethod() {
      String string = "parent method";
      return string
   }


   static class ChildUtil {

      public static String childMethod() {
         String string = "child method";
         return string;
      }

   }

}

控制器看起来像这样:

import app.structure.here.ParentUtil

@Controller
public Class FeatureController
{
     private ParentUtil parentUtil;

     @PostMapping("/url")
     public ResponseEntity<String> getTestData() {

          // here is where I need the string from the utilities class
          String string = parentUtil.parentMethod(); // this does not work
          String string = ParentUtil.parentMethod(); // this works

          // but what I really want is the string generated by the ChildUtil
          String string = parentUtil.childUtil.childMethod(); // doesn't work
          String string = childUtil.childMethod(); // doesn't work
          String string = ParentUtil.childUtil.childMethod(); // doesn't work
          String string = ChildUtil.childMethod(); // doesn't work
          String string = ParentUtil.ChildUtil.childMethod(); // doesn't work

          return new ResponseEntity<String>(string,HttpStatus.OK);
     }

     public FeatureController(ParentUtil parentUtil)
     {
         this.parentUtil = parentUtil;
     }
}

如何访问静态子类中的静态方法?我觉得自己像个白痴。

【问题讨论】:

  • 您不能从实例访问静态方法。如果你真的需要这个,你可能应该做 ParentUtil.ChildUtil.childMethod() 通过实际的类而不是类的实例来引用它们。刚刚看到您已经尝试过了,但是我们需要一些错误消息来提供帮助。

标签: java spring


【解决方案1】:

这是访问静态内部类方法的运行示例。

可能您的课程的可见性有问题(您的示例甚至拼写错误为班级)。您应该解释一下您的可见性用例是什么,也许您有我们不知道的要求。

package a;

public class A {

    public static void a() {
        System.out.println("a");
    }

    public static class Aa {

        public static void aa() {
            System.out.println("aa");
        }
    }
}

package b;

import a.A;

public class B {
    
    public static void main(String[] arg) {
        new B().b();
    }

    void b() {
        A.a();
        A.Aa.aa();
    }
}

Output:
a
aa

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多