So I am making a server, a lot like IRC, just to learn more, and here’s my problem.
I have commands that each person can call depending on their rights, and each “command” has it’s own class all located in one directory. I load all the classes into a HashMap, and it all works great if I add NEW commands, but if I change an old one, nothing changes in it.
So how can I use a URLClassLoader to load classes without caching them?
Thanks for any help.
This is the code I’m using
ClassLoader loader = new URLClassLoader(scriptURLS);
try {
for(URL u : scriptURLS) {
if(u == null) continue;
String fileName = u.getFile();
int beginIndex = fileName.indexOf("commands/") + 9;
int endIndex = fileName.indexOf(".c");
fileName = fileName.substring(beginIndex, endIndex);
String name = fileName.toLowerCase();
Class<Command> c = (Class<Command>) loader.loadClass("chat.commands."+fileName);
I realize it’s not the cleanest or the most efficient code out there, but it works.
You should be very careful creating your own classloaders as you could quickly run out of PermGen space as a result of circular references in memory that prevent the Garbage Collector from reclaiming the space taken by previous loaders (that is something to be careful of if you decide to dump your ClassLoader and create a new one every time you need to reload commands). More information on how that occurs here:
http://www.zeroturnaround.com/blog/rjc201/
If you have not already, you should take a look at JRebel. There is a license fee, but I think it may solve your problem:
http://www.zeroturnaround.com/jrebel/
Also, the java HotSwap (used for the java debugging API) may have hooks to facilitate this hot-redeploy behavior you’re looking for (usually available in IDE environments).
I don’t fully understand your use case to be honest (why do you have to load the Command classes at runtime, and why do you need the hot-deploy behavior).