Dynamic loading a class in java with a different package name
- by C. Ross
Is it possible to load a class in Java and 'fake' the package name/canonical name of a class? I tried doing this, the obvious way, but I get a "class name doesn't match" message in a ClassDefNotFoundException.
The reason I'm doing this is I'm trying to load an API that was written in the default package so that I can use it directly without using reflection. The code will compile against the class in a folder structure representing the package and a package name import. ie:
./com/DefaultPackageClass.class
// ...
import com.DefaultPackageClass;
import java.util.Vector;
// ...
My current code is as follows:
public Class loadClass(String name) throws ClassNotFoundException {
if(!CLASS_NAME.equals(name))
return super.loadClass(name);
try {
URL myUrl = new URL(fileUrl);
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();
while(data != -1){
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();
return defineClass(CLASS_NAME,
classData, 0, classData.length);
} catch (MalformedURLException e) {
throw new UndeclaredThrowableException(e);
} catch (IOException e) {
throw new UndeclaredThrowableException(e);
}
}