有 Java 编程相关的问题?

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

HashMap中特定于Java存储的类类型

我正在尝试实现一个命令行界面,您可以在其中搜索市场上的产品

为了允许多个市场,我实现了一个市场接口。我计划使用一个哈希映射,将市场名称(例如Amazon)映射到实现市场接口的类

public interface Marketplace {

    static ArrayList<Product> searchForProduct(String productName) {
        throw new IllegalStateException("searchForProduct hasn't been defined");
    };

    static ArrayList<Listing> getListings(Product product) {
        throw new IllegalStateException("getListings hasn't been defined");
    }
}

如何将实现marketplace类的类作为值存储在哈希映射中,然后从哈希映射中获取该类并调用其中一个静态方法


共 (1) 个答案

  1. # 1 楼答案

    我想你想要这样的东西:

    Map<String, Class<? extends Marketplace>> descriptionsToClasses = new HashMap<>();
    
    descriptionsToClasses.put("Amazon Marketplace", Amazon.class);
    

    最后,调用静态方法:

    Class<? extends Marketplace> marketplaceClass = descriptionsToClasses.get("Amazon Marketplace");
    Method staticSearchMethod = marketplaceClass.getMethod("searchForProduct", String.class);
    staticSearchMethod.invoke(null, "foo");
    

    确保调用的静态方法在作用域中可见