2

I'm making a service that watches a certain directory and when it detects changes in code in that directory, it runs all the tests in the directory. Purpose is that it runs the tests on the changes in code in that directory. So if I add a new method in a class and then a new test, it should use the new class and new test and include it in its testrun.

How can I do this dynamically? I can dynamically load all the test classes, by scanning the directory and collecting the tests and using my own custom dynamic loader ( as done by Reload used classes at runtime Java ). But the classes remain the ones before the changes. Before the service started watching, i.e before runtime.

How can I force those classes used in the tests to also be dynamically loaded?

Community
  • 1
  • 1
Sven
  • 1,133
  • 1
  • 11
  • 22

1 Answers1

2

It seems to me that you want to reload a class once it was changed at runtime. You should have a look at this article. The problem with this approach is, that the reloaded class will not be the same anymore, because you can't use the same ClassLoader twice and using another classloader will result in the classes not being the same anymore and ultimately causing ClassCastExceptions.

This can be avoided by programming against interfaces, but you might have to change your class design.

In case you want to reload all referenced classes as well, you probably need to override ClassLoader.findClass(String name). I cannot test this pretty specific scenario now, but I assume that this method is called for all referenced classes. Since the default implementation will just throw a ClassNotFoundException, the parent class loader will be asked to find the class and it will give you the old version.

You could try this:

protected Class<?> findClass(String name) throws ClassNotFoundException {
   return loadClass(name);
}
noone
  • 19,520
  • 5
  • 61
  • 76
  • I've used this article also, but it doesn't reload the classes in the test classes! I can reload a given class all I want but not the classes that given class uses. – Sven Nov 21 '13 at 20:55
  • @Sven I changed the answer a bit. I cannot test it myself at the moment. – noone Nov 21 '13 at 21:22