NoClassDefFoundError when adding classes to the classpath at runtime when I used abstract or interface in Main class

I know Java loads Classes in first Access (creating new Instance, calling static method or static field), but in this simple example I try to execute a jar file that uses some classes which there aren't in my ClassPath at run time. I expect (because of loading classes in first access) print my messages in static block and main method before an exception occurred. but I got "Exception in thread "main" java.lang.NoClassDefFoundError: com/example/DateAbstract" and nothing printed. This occurred when I used an abstract class or interface in main class which that classes or interfaces are in another jar file.

public class Driver { static { System.out.println("I am first.[static block]"); } public static void main(String[] args) {     System.out.println("I am first.[ main method]");     DateAbstract date = new CustomDate();     System.out.println(date.sayDate()); } 

in my another jar :

public class CustomDate extends DateAbstract { @Override public String sayDate() {     return new Date().toString(); } public abstract class DateAbstract { public abstract String sayDate();  } 

when I use this code for add my classes to classpath at runtime. nothing changed. I got execption before execute static block.

public class Driver { static {     System.out.println("I am first.[static block]");     try {         URL url = new File("lib/DateApi.jar").toURI().toURL();         URLClassLoader urlClassLoader = (URLClassLoader) URLClassLoader.getSystemClassLoader();         Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);         method.setAccessible(true);         method.invoke(urlClassLoader,url);     } catch (Exception e) {         e.printStackTrace();     }  } public static void main(String[] args) {     System.out.println("I am first.[ main method]");     DateAbstract date = new CustomDate();     System.out.println(date.sayDate()); }  } 

Questions : why is this happening and how to solve it ?

Replay

Category: java Time: 2016-07-30 Views: 0

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.144 (s). 12 q(s)