加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 无法从静态上下文引用非静态字段 – 主方法

发布时间:2020-12-15 01:05:39 所属栏目:Java 来源:网络整理
导读:参见英文答案 Non-static variable cannot be referenced from a static context????????????????????????????????????12个 我的Spring-Boot应用程序中有2个类: -任务 -Runner runner类包含我的main方法,我尝试从Tasks类调用一个方法: 亚军: @Componentpu

参见英文答案 > Non-static variable cannot be referenced from a static context????????????????????????????????????12个
我的Spring-Boot应用程序中有2个类:

-任务

-Runner

runner类包含我的main方法,我尝试从Tasks类调用一个方法:

亚军:

@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();

    }

任务类:

@Service
public class Tasks {

    public void createTaskList() {

    //my code
    }


    //other methods 


}

在我的Runner中,当我尝试在Tasks类中调用createTaskList()方法时,我收到以下错误:

Non static field 'tasks' cannot be referenced from a static context

我怎么解决这个问题?

最佳答案
主要方法是静态意味着它属于类而不是某个对象.因此,静态上下文不能引用实例变量,因为如果有一个实例变量,它将不知道它将使用哪个Runner实例.

简而言之,解决方案是使您的Tasks对象在Runner类中保持静态.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读