问题
I have below interface and its implementation class.
Demo.java
public interface Demo{
void showDemo();
}
DemoImpl.java
@Service
public class DemoImpl implements Demo{
public void showDemo(){
//To Do
}
}
Now i have one class with static method which will internally call showDemo()
as below.
DemoStatic.java
@Component
public class DemoStatic{
@Autowired
private Demo demo;
public static void callShowDemo(){
demo.showDemo(); //calling non static method from static method
}
}
Here i am calling non static method from static method. Is my design correct? Or do i need to change my design? Please suggest me.
Thanks!
回答1:
No your design is not correct.
private Demo demo;
has to be
private static Demo demo;
You just cant use NON static members in a static method
回答2:
You can do it this way
@Component
public class DemoStatic {
private static Demo demo;
@Autowired
public void setDemo(Demo d) {
demo = d;
}
public static void callShowDemo(){
demo.showDemo(); //calling static method from static method
}
}
回答3:
The above code will not compile at all. You are trying to refer non-static reference from static method, which is not allowed in Java.
Refer this stackoverflow link for better understanding.
Make the following change:
public static Demo demo;
回答4:
when you call DemoStatic.callShowDemo(),the demo may not been instand
来源:https://stackoverflow.com/questions/19946852/calling-non-static-method-from-static-class-in-java-with-spring-autowiring