Hello, I have this class to reload classes:
the class BotMethods:Code:// Ripped from http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
import java.io.*;
import java.net.*;
public class MyClassLoader
extends ClassLoader
{
public MyClassLoader(final ClassLoader parent) {
super(parent);
}
public Class loadClass(final String name) throws ClassNotFoundException {
if (!name.equals("BotMethods"))
return super.loadClass(name);
System.out.println("IN");
try {
String url = "file:BotMethods.class";
URL myUrl = new URL(url);
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();
System.out.println("OUT1");
return defineClass("BotMethods",classData,0,classData.length);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("OUT2");
return null;
}
}
And the main class:Code:import java.net.*;
import java.io.*;
public class BotMethods
{
// Only methods
}
Which throws this error:Code:import java.net.*;
import java.io.*;
import java.awt.*;
import java.lang.reflect.*;
public class JavaBot
{
private JavaBot() {
reloadMethods();
}
public void reloadMethods() {
try {
ClassLoader parentClassLoader = MyClassLoader.class.getClassLoader();
MyClassLoader classLoader = new MyClassLoader(parentClassLoader);
Class myClass = classLoader.loadClass("BotMethods");
BotMethods bm1 = (BotMethods)myClass.newInstance(); // Error here
//create new class loader so classes can be reloaded.
classLoader = new MyClassLoader(parentClassLoader);
myClass = classLoader.loadClass("BotMethods");
bm1 = (BotMethods)myClass.newInstance();
bm = bm1;
//bm = new BotMethods();
}
catch (Exception e) {
System.out.println("Could not reload methods");
e.printStackTrace();
//BotMethods.say(bout,"Matt","Could not reload methods: "+e);
}
}
public static void main(String[] args) {
new JavaBot();
}
}
Why does it throw this error and how to fix it?Quote:
java.lang.ClassCastException: BotMethods cannot be cast to BotMethods
To clarify things: I want the class BotMethods to be reloaded without having to restart the application, so that I can add methods and such while running, which can be executed right after I called the reloadMethods method. I know this is possible, I'm just not sure how.
Please help. :)
Thanks,
~Matt
