在类路径上查找泛型接口的具体实现

Finding specific implementation of generic interface on classpath

我最近(两次)遇到了以下问题 - 是否可以在 classpath 上找到通用接口的特定实现?要形象化这一点,请考虑以下代码片段:

public interface Cleaner<T extends Room> {}
public class KitchenCleaner implements Cleaner<Kitchen> {}
public class BathroomCleaner implements Cleaner<Bathroom> {}

现在 - 是否可以有以下方法?:

public static <T extends Room> findCleanerServiceForRoomType(T room) {
    return ???
}

返回厨房的 KitchenCleaner class 和浴室的 BathroomCleaner class?当然,我希望它可以扩展,以便在添加新的房间和服务类型时,此方法仍然有效...所以没有开关或 ifs :)

由于泛型不存在于编译之外,所以这个问题的答案是否定的

由于泛型会在运行时擦除类型,因此我建议您在接口中放置一个泛型方法以返回已清理的房间:

public Class<? extends Room> getCleanedClass(){
    //override in every implementation
    return Kitchen.class;
}

然后您可以在此方法上使用谓词。

您可以向 Room 定义(接口或抽象 class)添加一个方法,为您提供合适的清洁器。由于添加房间时需要添加Cleaner,所以没有额外配置。

public interface Room {
  Cleaner<? extends Room> cleanerInstance();
}

public class Bathroom implements Room {
  public Cleaner<Bathroom> cleanerInstance(){
    return new BathroomCleaner();
  }
}

如果您想在 Room 不知情的情况下找到它,您需要进行某种配置或查找。