gpt4 book ai didi

java - Spring无法对非静态方法进行静态引用?

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:10 24 4
gpt4 key购买 nike

这是我的 PageController 代码。

@RequestMapping(value = { "/show/category/{id}/products" })
public ModelAndView showCategoryProducts(@PathVariable("id") int id) {

// Category DAO //Getting Error Here
Category category = null;//Please Explain this line also.
category = CategoryDAO.get(id);// Getting Error in this line

ModelAndView mv = new ModelAndView("page");
mv.addObject("title", "All Products");
// Passing list of categories
mv.addObject("categories", categoryDAO.list());
mv.addObject("userClickCategoryProducts", true);
return mv;
}

CategoreDAO 类中的代码

public interface CategoryDAO {
List<Category> list();
Category get(int id);
}

另一个实现 CategoryDAO 类的类

Repository("CategoryDAO")
public class CategoryDAOImpl implements CategoryDAO {
private static List<Category> categories = new ArrayList<>();

static {@Override
public Category get(int id) {

for(Category category:categories) {
if(category.getId()==id)
return category;
}

return null;
}

我收到一个错误,指出静态引用无法创建非静态方法。

请查看第一个代码片段。你就会明白这个问题了

最佳答案

是的,绝对。

静态和非静态对象的工作方式不同。对于非静态方法,必须在使用之前实例化。这就是为什么在静态方法中使用非静态方法是无效的。

还有一件事,静态 block 将在构造函数之前调用。因此,请仔细检查您的业务逻辑。我不太明白为什么要重写静态 block 中的其他函数。

关于java - Spring无法对非静态方法进行静态引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52457851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com