微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java:自实例化类

如何解决Java:自实例化类

我正在用 Java 为一个大学项目构建一个匹配工具,该项目基本上只是由几个更简单的匹配算法的集合组成。现在我希望人们能够轻松地添加他们自己的算法,并通过将 .java 文件添加到项目文件夹中来自动将它们包含到集合中。

每个算法都必须实现一个 MatchingComponentInterface,我想实现的是,每个实现这个接口的类都告诉集成它存在,以便集成可以动态地组装自己,包括该算法。

举个简单的例子,让主代码和整体代码看起来像这样:

class Main {
  @Getter
  private Ensemble ensemble = new Ensemble();

  public static void main(String[] args){
    //SomeMatchingComponent.touch();
    Result res = ensemble.match(args[0],args[1]);
  }
}

请注意注释中的 touch() 调用,我稍后再讲。

public class Ensemble{

  private List<MatchingComponentInterface> components;
  private Result combinedResult = new Result();

  public void addComponent(MatchingComponentInterface component){
    components.add(component);
  }

  public void match(Object first,Object second){
    components.forEach(component -> {
      combinedResult.addResult(component.match(first,second));
    });
  }
}

此外,我可能有几个类似这样的 MatchingComponent 实现:

public class SomeMatchingComponent implements MatchingComponentInterface{

  //this is only executed the first time the class is mentioned in the code
  //however I want this do be executed without mentioning the class
  static {
    MatchingComponent foo = new MatchingComponent();
    Main.getEnsemble().addComponent(foo);
  }

  //static void touch(){}

  public Result match(Object first,Object second){
    //matching magic
  }
}

现在来看看静态代码块。只要我在代码中的其他地方使用该类,就会执行此代码。但是在本例中,这不会发生,因为我注释掉了 touch() 方法以及 main 方法中的调用

当集成构建时,主要方法需要事先知道所有组件,以便触摸并将它们添加到集成中。但是我想在没有任何这些的情况下添加它们。他们应该添加自己。

我现在的问题是:有没有办法强制执行静态代码块,而无需硬编码存在哪些组件,或者让接口调用自身的所有实现?

解决方法

我实际上已经找到了一种以编程方式解决该问题的解决方案。使用 reflections 库可以检测任何类的所有子类或任何接口的实现,因此通过一些这样的代码,我可以实现我需要的:

public void addAllComponents(Ensemble ensemble){

  //"matching.component" is a prefix as all components are in a package with that name
  Reflections reflections = new Reflections("matching.component");
  Set<Class<? extends MatchingComponentInterface>> classes 
    = reflections.getSubTypesOf(MatchingComponentInterface.class);
  
  classes.forEach(aClass -> {
    try{
      ensemble.addComponent(aClass.getConstructor().newInstance());
    } 
    catch (NoSuchMethodException | IllegalAccessException | 
          InstantiationException | InvocationTargetException e) {
      //Handle exceptions appropriately
    }
  });
}

我在一个非常古老的问题中找到了这个库:

How can I get a list of all the implementations of an interface programmatically in Java?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。