SpringBoot REST API开发报错:无法静态引用Course类的非静态getId()方法
解决SpringBoot中"cannot make a static reference to the non-static method getId()"报错
问题场景
作为SpringBoot新手,在编写第一个REST API示例时,实现类代码出现编译错误:cannot make a static reference to the non-static method getId() from the type Course,原本期望代码能正常编译。
错误代码(实现类)
@Override public Course getCourse(long courseId) { Course c=null; for (Course course:list) { if(Course.getId()==courseId) { c=course; break; } } return c; }
错误原因
报错的核心是用类名Course调用了非静态方法getId()。非静态方法属于类的实例对象,必须通过具体的对象实例来调用,而非直接用类名调用。
修正后的实现类代码
@Override public Course getCourse(long courseId) { Course c=null; for (Course course:list) { // 改用循环中的course实例调用getId() if(course.getId()==courseId) { c=course; break; } } return c; }
补充相关代码(供参考)
控制器类
@GetMapping("/courses/{courseId}") public Course getCourse(@PathVariable String courseId) { return this.courseService.getCourse(Long.parseLong(courseId)); }
服务类接口
public interface CourseService { public List<Course> getCourses(); public Course getCourse(long courseId); }
实体类
public class Course { private long id; private String title; private String description; public Course(long id, String title, String description) { super(); this.id = id; this.title = title; this.description = description; } public long getId() { return id; } }
内容的提问来源于stack exchange,提问作者Merlion Curry
相关产品推荐
相关产品推荐

