I have a base and sub class. The requirement is to invoke sub class' method using reflection. Both programs are below.
base.java
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
public class base {
public static void main(String[] args) {
URLClassLoader loader = null;
Class<?> cls;
try {
File file = new File("sub.jar" );
URL[] urls = { file.toURI().toURL() };
loader = new URLClassLoader(urls);
cls = loader.loadClass("sub");
base obj = (base) cls.newInstance();
obj.print();
}
catch(Exception e) {
System.out.println("Exception occured:" + e);
e.printStackTrace();
}
}
public void print() {
System.out.println("In Base class");
}
}
sub.java
public class sub extends base {
public void print() {
System.out.println("In subclass");
}
}
compile both in to jars.
javac base.java;
jar cvf base.jar base.class
javac sub.java;
jar cvf sub.jar sub.class
If I invoke the base.jar as "java -cp", it works fine
java -cp base.jar base
output: "In subclass"
But if I invoke it with "hadoop jar" command, I get
hadoop jar base.jar base
Exception in thread "main" java.lang.NoClassDefFoundError: base
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at base.main(base.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by: java.lang.ClassNotFoundException: base
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
Any help is greatly appreciated.
Aucun commentaire:
Enregistrer un commentaire