ClassNotFoundException vs NoClassDefFoundError

前端 未结 9 1892
半阙折子戏
半阙折子戏 2020-12-23 11:59

I have gone through this thread What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException? This is what one of the ans,which has max u

9条回答
  •  萌比男神i
    2020-12-23 12:44

    NoClassDefFoundError is usually called when you are using a library(for example, Guava, Gson, CommonsIO). You put the library in classpath of your project, but you didn't export it together, you will get a NoClassDefFoundError when the application is running.

    How to get NoClassDefFoundError:
    Create a new project, with this class.

    public class A
    {
        public void do()
        {
            System.out.println("Do!");
        }
    }  
    

    Export it as a .jarfile.

    Now create another project. Add the exported jar file to classpath.

    import ???.A;
    public class Main
    {
        public static void main(String[] args)
        {
            A a = new A();
            a.do();//NoClassDefFoundError thrown at here.
        }
    } 
    

    Export the project, make sure you do not include the jar file(with class A). Run the newly exported jar file, you will see that error!

提交回复
热议问题