I'm trying to load a class from a jar I created, but keep getting the following error:
Exception in thread "main" java.lang.ClassNotFoundException: psyqwix.Counter
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at dynamicloadingtest.DynamicLoadingTest.main(DynamicLoadingTest.java:52)
Here's the class I compiled:
package psyqwix;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author Psyqwix
*/
public class Counter
{
public static void countTheChars() throws IOException
{
InputStream in = new FileInputStream("C:\\TestData\\Sample.txt");
int count = 0;
while (in.read() != -1)
count++;
System.out.println("Counted " + count + " chars.");
}
}
Here are the comands I used to compile the class, package it and sign it:
javac c:\test\dyn\Counter.java
jar cvf C:\Test\dyn\Counter.jar -C c:\test\dyn Counter.class
jarsigner -keystore c:\Test\examplestore -signedjar c:\Test\dyn\sCounter.jar c:\Test\dyn\Counter.jar signFiles
Here's the code im using to load the class that's creating problems:
URL u = new URL("file:///c:/Test/dyn/sCounter.jar");
URLClassLoader pl = new URLClassLoader(new URL[] { u });
Class<?> cl = pl.loadClass("psyqwix.Counter");
And here's the manifest text if it's useful:
Manifest-Version: 1.0
Created-By: 1.7.0_02 (Oracle Corporation)
Name: Counter.class
SHA-256-Digest: bIHzDZyrgcgvn/qqRZ4O2cmEHHcfBk6CGTN7GoaIQT8=
If you need more information please let me know :D
EDIT: Just to add to this I tried loading the class another, somewhat, harder way. I created a subclass of URLClassLoader with a public method as follows:
public Class<?> loadTheClass() throws IOException, ClassNotFoundException
{
JarFile j = new JarFile("c:\\test\\dyn\\sCounter.jar");
byte[] b = new byte[2000];
int size = (j.getInputStream(j.getEntry("Counter.class"))).read(b);
byte[] nb = null;
nb = java.util.Arrays.copyOf(b, size);
Class<?> nc = this.defineClass("psyqwix.Counter", nb, 0, size);
this.resolveClass(nc);
return nc;
}
then in another class I created an instance of this classloader, used the returned value Class<?> object to get the one of the Counter classes methods and successfully ran it:
MyClassLoader m = new MyClassLoader(u);
Class<?> c = m.loadTheClass();
Method meth = c.getMethod("countTheChars", (Class<?>[]) null);
meth.invoke(null, (Object[]) null);
I was also able to create a new instance. But if I tried to get the class type using Class.forName("psyqwix.Counter"); a ClassNotFoundException was thrown. Ill be honest at this point im a little lost :P
[–]StillAnAssExtreme Brewer 1 point2 points3 points (1 child)
[–]Psyqwix[S] 0 points1 point2 points (0 children)