I have 2 classes in my Spring-Boot
application:
-Tasks
-Runner
The runner class contains my main
method where I try to call a method from my Tasks class:
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:
Non static field 'tasks' cannot be referenced from a static context
How can I solve this?
Of course, they can but the opposite is not true i.e. you cannot access a non-static member from a static context i.e. static method. The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs.
i.e. referring a variable using static reference implies to referring using the class name. But, to access instance variables it is a must to create an object, these are not available in the memory, before instantiation. Therefore, you cannot make static reference to non-static fields(variables) in Java.
You cannot assign the result of a non-static method to a static variable. Instead, you would need to convert the getIPZip method to be a static method of your MyProps class, then you could assign its result to yor IPZip variable like this. public static String IPZip = MyProps. getIPZip("IPZip");
You cannot call non-static methods or access non-static fields from main or any other static method, because non-static members belong to a class instance, not to the entire class.
The main method is static
meaning 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 Runner
it would use if there even was one.
In short, the solution is to make your Tasks
object static
in the Runner
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With