class.getconstructor找不到兼容的构造函数

e37o9pze  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(393)

如果工厂类有问题,我传入一个人类可读的名称,该名称Map到一个具有单个构造函数和单个参数的类,则会出现以下错误:

java.lang.NoSuchMethodException: com.satgraf.evolution2.observers.VSIDSTemporalLocalityEvolutionObserver.<init>(com.satlib.evolution.ConcreteEvolutionGraph)
at java.lang.Class.getConstructor0(Class.java:2892)
at java.lang.Class.getConstructor(Class.java:1723)
at com.satlib.evolution.observers.EvolutionObserverFactory.getByName(EvolutionObserverFactory.java:84)
at com.satgraf.evolution2.UI.Evolution2GraphFrame.main(Evolution2GraphFrame.java:229)

这些都是有问题的课程,我在不同的项目中有十几个这样的东西,它们都可以毫无问题地工作——包括一个几乎相同的课程,我不明白为什么这个课程会失败:

public EvolutionObserver getByName(String name, EvolutionGraph graph){
if(classes.get(name) == null){
  return null;
}
else{
  try {
    Constructor<? extends EvolutionObserver> con = classes.get(name).getConstructor(graph.getClass());
    EvolutionObserver i = con.newInstance(graph);
    observers.add(i);
    return i;
  } 
  catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException | IllegalArgumentException | SecurityException ex) {
    Logger.getLogger(EvolutionObserverFactory.class.getName()).log(Level.SEVERE, null, ex);
    return null;
  }
}
}

正在示例化的类是:

public class VSIDSTemporalLocalityEvolutionObserver extends JPanel implements EvolutionObserver{
    public VSIDSTemporalLocalityEvolutionObserver(EvolutionGraph graph){
    ...
    }
...
}

争论 graph 类型为:

public class ConcreteEvolutionGraph extends ConcreteCommunityGraph implements EvolutionGraph{
    ...
}
pjngdqdw

pjngdqdw1#

getConstructor 要求参数类型完全匹配;它不会试图找到“兼容”构造函数。这个 getConstructor javadoc只是说“要反映的构造函数是这个类对象所表示的类的公共构造函数,它的形式参数类型与 parameterTypes “(在当前openjdk中, getConstructor 代表 getConstructor0 循环遍历所有构造函数并将给定的参数数组与 constructor.getParameterTypes() .)
在运行时,您的代码将查找接受类型为的参数的构造函数 ConcreteEvolutionGraph ( graph.getClass() 退货 graph 的运行时类型),以及 VSIDSTemporalLocalityEvolutionObserver 没有。
如果你真的想找一个 EvolutionGraph ,通过 EvolutionGraph.classgetConstructor 相反。如果您想要任何可以用图形的运行时类型调用的构造函数,则需要手动循环 getConstructors() 寻找一个单参数构造函数 graph.getClass().isAssignableTo(ctor.getParameterTypes()[0]) . 注意可能不止一个,当涉及到接口时,可能没有最具体的接口。你得决定如何打破关系。

相关问题