How to load a jar file at runtime [duplicate]

Reloading existing classes with existing data is likely to break things. You can load new code into new class loaders relatively easily: ClassLoader loader = URLClassLoader.newInstance( new URL[] { yourURL }, getClass().getClassLoader() ); Class<?> clazz = Class.forName(“mypackage.MyClass”, true, loader); Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class); // Avoid Class.newInstance, for it is evil. Constructor<? extends Runnable> … Read more

Scanning Java annotations at runtime

Use org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider API A component provider that scans the classpath from a base package. It then applies exclude and include filters to the resulting classes to find candidates. ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>); scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class)); for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>)) System.out.println(bd.getBeanClassName());

What is the difference between Class.getResource() and ClassLoader.getResource()?

Class.getResource can take a “relative” resource name, which is treated relative to the class’s package. Alternatively you can specify an “absolute” resource name by using a leading slash. Classloader resource paths are always deemed to be absolute. So the following are basically equivalent: foo.bar.Baz.class.getResource(“xyz.txt”); foo.bar.Baz.class.getClassLoader().getResource(“foo/bar/xyz.txt”); And so are these (but they’re different from the above): … Read more

Unloading classes in java?

The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo. One possible solution to your problem is to have a Classloader for every jar file, and a Classloader … Read more

How to load JAR files dynamically at Runtime?

The reason it’s hard is security. Classloaders are meant to be immutable; you shouldn’t be able to willy-nilly add classes to it at runtime. I’m actually very surprised that works with the system classloader. Here’s how you do it making your own child classloader: URLClassLoader child = new URLClassLoader( new URL[] {myJar.toURI().toURL()}, this.getClass().getClassLoader() ); Class … Read more