有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用数组。asList()方法返回对象列表?

我正在使用Spring boot设置RestController。这个项目要求我返回一个对象列表(在本例中是类Book的对象)。我该怎么做

我试过数组。asList()方法,通过传递如下所示的类Book的对象:

java

@RestController
public class BookController {

    @GetMapping("/books")
    public List<Book> getAllBooks() {

        return Arrays.asList(new Book(1l, "Book name", "Book author"));

    }
}

java

public class Book {

    Long id;
    String name;
    String author;

    public Book(Long id, String name, String author) {
        super();
        this.id = id;
        this.name = name;
        this.author = author;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getAuthor() {
        return author;
    }

    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + ", author=" + author + "]";
    }
}

我有这个错误"Type mismatch: cannot convert from List<Object> to List<Book>"。我怎样才能解决这个问题


共 (1) 个答案

  1. # 1 楼答案

    这在我身上发生过好几次,原因总是IDE以某种方式自动从junit包导入了其他Arrays类,而不是从java导入的。util。 因此,检查您的导入部分,如果导入了另一个Arrays类,则放入import java.util.Arrays;。 @Tom Hawtin-tackline提出了类似的建议,但除了正确的导入之外,不需要其他任何东西