Java 代码报错:Cannot make a static reference to the non-static method

在你的代码片段中:

if (captcha != null && captcha.equalsIgnoreCase(sessionCaptcha)) {
    response.getWriter().write('验证码正确');
    
    com.Test.demo1.tjChaXun();
    
} else {
    response.getWriter().write('验证码错误');
}

你遇到了 Cannot make a static reference to the non-static method tjChaXun() from the type demo1 的错误。

原因:

这个错误是因为你在静态方法中调用了一个非静态方法 tjChaXun()。在 Java 中:

  • 静态方法属于类,可以通过类名直接调用。
  • 非静态方法属于对象,需要先创建类的实例,然后通过实例调用。

由于静态方法在没有实例的情况下也可以被调用,因此无法在静态方法中直接调用非静态方法,因为它不知道要使用哪个对象的 tjChaXun() 方法。

解决方法:

要解决这个问题,你需要创建一个 demo1 类的实例,然后使用该实例调用 tjChaXun() 方法。修改后的代码如下:

if (captcha != null && captcha.equalsIgnoreCase(sessionCaptcha)) {
    response.getWriter().write('验证码正确');
    
    demo1 obj = new demo1();
    obj.tjChaXun();
    
} else {
    response.getWriter().write('验证码错误');
}

通过创建 demo1 类的实例 obj,你就可以在静态方法中调用非静态方法 tjChaXun() 了。


原文地址: https://www.cveoy.top/t/topic/f1Et 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录