如果是instanceof,则强制转换为特定子级。有什么更好的办法吗?

问题描述 投票:0回答:1

将 Parent 发送到方法,然后在数据库中查找 AllBy 类似产品。

我的数据库有 3 个表。产品,加入佐餐啤酒和加入薯条

class Product {
    String name;
    String type;
    int actualAmount;
    int goalAmount;
}

class Beer extends Product {
    int liters;
    int percentage;
}

class Chips extends Product {
    int weight;
    String taste;
}

class ProductService {
    private final ProductRepository repo;

    //Send parent to method then getAll similar products by child variables.
    public void foo(Product product) {
        if (product instanceof Beer) {
            Beer beer = (Beer) product;
            List<Beer> fromDb = repo.findAllByPercentage(beer.getPercentage());
        }

        else if (product instanceof Chips) {
            Chips chips = (Chips) product;
            List<Chips> fromDb = repo.findAllByTaste(chips.getTaste());
        }
    }
}
java spring spring-boot inheritance polymorphism
1个回答
0
投票

从 Java 17 开始(我认为)你可以这样做:

if (product instanceof Beer beer) {
    List<Beer> fromDb = repo.findAllByPercentage(beer.getPercentage());
} else if (product instanceof Chips chips) {
    List<Chips> fromDb = repo.findAllByTaste(chips.getTaste());
}
© www.soinside.com 2019 - 2024. All rights reserved.