我試圖在頂級Main class
內調用2個不同版本的相同依賴庫(jars
)。所以我創建了一個具有2個實現類的接口,兩個類都有一個使用普通API的運行方法,一個將使用somejar-1.0.0-SNAPSHOT.jar
,另一個將通過顯式調用ClassLoader使用somejar-2.0.0-SNAPSHOT.jar
。java.lang.NoSuchMethodException Java
public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
ClassLoader loader1 = new URLClassLoader(new URL[] { new File("/Users/haddad/.m2/repository/com/company/somejar-1.0.0-SNAPSHOT.jar").toURL() });
ClassLoader loader2 = new URLClassLoader(new URL[] { new File("/Users/haddad/.m2/repository/com/company/somejar-2.0.0-SNAPSHOT.jar").toURL() });
Class<?> c1 = loader1.loadClass("com.engine.na.EngineV1");
Class<?> c2 = loader2.loadClass("com.engine.na.EngineV2");
IEngine app1 = (IEngine) c1.newInstance();
IEngine app2 = (IEngine) c2.newInstance();
Integer s1 = app1.run();
Integer s2 = app2.run();
Assert.equals(s1,s2,"Outputs from somejar-1.0 and somejar-2.0 did not match, perhaps somejar-2.0 has regressed?");
}
這裏有EngineV1和V2與接口:
public Interface IEngine {
Integer run();
}
public class EngineV1 implements IEngine {
private File content;
private File en;
public EngineV1(args) {
this.content = new File("/some/path");
this.en = new File("/some/path");
}
public static void main(String[] args) {
new EngineV1(args).run();
}
public Integer run() {
// some logic...
somejar.evaluateSpeed();
}
}
public class EngineV2 implements IEngine {
private File content;
private File en;
public EngineV2(args) {
this.content = new File("/some/path");
this.en = new File("/some/path");
}
public static void main(String[] args) {
new EngineV2(args).run();
}
public Integer run() {
// some logic...
somejar.evaluateSpeed();
}
}
當我去運行主類,我得到:
Exception in thread "main" java.lang.InstantiationException: com.engine.na.EngineV1
at java.lang.Class.newInstance(Class.java:427)
at com.engine.na.MainClass.main(MainClass.java:23)
Caused by: java.lang.NoSuchMethodException: com.engine.na.EngineV1.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
... 1 more
爲什麼我得到這個錯誤?如何解決這個問題?
給你一個類的默認構造函數。 – pvg
不是java隱式地爲EngineV1和EngineV2創建一個無參數構造函數? – mosawi
是Java在編譯時爲您生成它,但我認爲您在EngineV1中聲明瞭一個無參數構造函數。 – davidxxx