[英]Loading Class from Jar File : java.lang.InstantiationException
I got this code to instantiate a Life class from jar file: 我得到了以下代码以从jar文件实例化Life类 :
import com.life.Life;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
public class Main {
public static void main(String[] args) {
try{
File file = new File("Life.jar");
URL url = file.toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.life.Life");
Life life = (Life) cls.newInstance();
System.out.println("Message: "+life.getMessage());
}catch(Exception e){
e.printStackTrace();
}
}
}
Here's the content of the Life.jar 这是Life.jar的内容
public class Life {
public String getMessage(){
return "Life is Beautiful!";
}
}
Here's my interface name Life 这是我的界面名称Life
package com.life;
public interface Life {
public String getMessage();
}
The code above will throw an error: 上面的代码将引发错误:
java.lang.InstantiationException: com.life.Life
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
at com.Main.main(Main.java:20)
BUILD SUCCESSFUL (total time: 0 seconds)
What's wrong with the code? 代码有什么问题? How to resolve this? 如何解决呢?
This happened because your interface is also named Life ( java tried to instantiate an interface). 发生这种情况是因为您的界面也被命名为Life(java试图实例化一个界面)。 Change public interface Life
to public interface LifeInterface
and then have your class Life implement that like : 将public interface Life
更改为public interface LifeInterface
,然后让您的类Life实现如下:
public class Life implements LifeInterface
{
@Override
public String getMessage()
{
return "Life is Beautiful!";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.