Java中'Cannot make a static reference to the non-static method' 错误解决方法
解决 Java 中 'Cannot make a static reference to the non-static method' 错误
在使用 Java 代码时,你可能会遇到类似 'Cannot make a static reference to the non-static method tjChaXun() from the type demo1' 的错误信息。这段错误信息表明你正在尝试从静态上下文中调用非静态方法。
问题背景
你可能在进行验证码校验后尝试调用 com.Test.demo1.tjChaXun(); 方法,但遇到了上述错误。这是因为 tjChaXun() 方法是非静态方法,而你试图在静态方法中直接调用它。
解决方法
将 tjChaXun() 方法修改为静态方法即可解决该问题。具体操作是在方法声明前添加 static 关键字:
public static void tjChaXun() {
// 方法体
}
修改后,你可以直接使用类名调用该方法:
demo1.tjChaXun();
代码示例
以下是修改后的完整代码示例,包括验证码校验和调用 tjChaXun() 方法的代码:
if (captcha != null && captcha.equalsIgnoreCase(sessionCaptcha)) {
response.getWriter().write('验证码正确');
demo1.tjChaXun();
} else {
response.getWriter().write('验证码错误');
}
public class demo1 {
public static void tjChaXun() {
// 方法体
}
}
通过将方法修改为静态方法,你就可以在静态上下文中成功调用它,从而解决 'Cannot make a static reference to the non-static method' 错误。
原文地址: https://www.cveoy.top/t/topic/f1Ev 著作权归作者所有。请勿转载和采集!