简体   繁体   中英

Loading Class from Jar File : java.lang.InstantiationException

I got this code to instantiate a Life class from jar file:

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

public class Life {

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

}

Here's my interface name 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). Change public interface Life to public interface LifeInterface and then have your class Life implement that like :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM