【发布时间】: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() 通过实际的类而不是类的实例来引用它们。刚刚看到您已经尝试过了,但是我们需要一些错误消息来提供帮助。