我得到了以下代码以从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();
         }
    }

}


这是Life.jar的内容

public class Life {

    public String getMessage(){
        return "Life is Beautiful!";
    }

}


这是我的界面名称Life

package com.life;

public interface Life {

    public String getMessage();

}


上面的代码将引发错误:

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)


代码有什么问题?如何解决呢?

最佳答案

发生这种情况是因为您的界面也被命名为Life(java试图实例化一个界面)。将public interface Life更改为public interface LifeInterface,然后让类Life实现为:

public class Life implements LifeInterface
{
   @Override
   public String getMessage()
   {
      return "Life is Beautiful!";
   }
}

关于java - 从Jar文件加载类:java.lang.InstantiationException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34845916/

10-11 15:39