java 不能从静态上下文引用非静态字段 - Main 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36841921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Non static field cannot be referenced from a static context- Main method
提问by java123999
I have 2 classes in my Spring-Bootapplication:
我的Spring-Boot应用程序中有 2 个类:
-Tasks
-任务
-Runner
-赛跑者
The runner class contains my mainmethod where I try to call a method from my Tasks class:
runner 类包含我main尝试从 Tasks 类调用方法的方法:
Runner:
赛跑者:
@Component
public class Runner {
Tasks tasks;
@Autowired
public void setTasks(Tasks tasks){
this.tasks=tasks;
}
public static void main(String[] args){
//error being caused by below line
tasks.createTaskList();
}
Tasks Class:
任务类:
@Service
public class Tasks {
public void createTaskList() {
//my code
}
//other methods
}
In my Runner, when I try to call the createTaskList() method in the Tasks class I get the following error:
在我的 Runner 中,当我尝试调用 Tasks 类中的 createTaskList() 方法时,出现以下错误:
Non static field 'tasks' cannot be referenced from a static context
How can I solve this?
我该如何解决这个问题?
采纳答案by Zircon
The main method is staticmeaning that it belongs to the class and not some object. As such, it a static context cannot reference an instance variable because it wouldn't know what instance of Runnerit would use if there even was one.
main 方法static意味着它属于类而不是某个对象。因此,它是一个静态上下文不能引用一个实例变量,因为它不知道Runner它会使用哪个实例,如果有的话。
In short, the solution is to make your Tasksobject staticin the Runnerclass.
简而言之,解决方案是在类中创建您的Tasks对象。staticRunner

