1

According to this question, it is possible to load a class from a jar file with:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { jarFileURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);

How to load all classes contained in a jar file?

Community
  • 1
  • 1
julien
  • 898
  • 3
  • 17
  • 32
  • 2
    why on earth do you want to do this? – mcfinnigan Sep 27 '11 at 15:21
  • Premature optimization? Can't tolerate latency in a critical section of code? Either way, better to just make an object of each of the "critical" ones before the critical section in such circumstances. – Edwin Buck Sep 27 '11 at 15:26
  • Here's a practical use case: if you write an update tool like getdown (http://code.google.com/p/getdown/) and you replace your own jar (ignoring that this might be a bit fragile), the class loaders we tried fails to load a new class (as the file handle got probably invalid). If we would pre-load all classes that are needed until the end of the updater, we're fine. – mringwal Dec 05 '12 at 10:32
  • 1
    Here is another practical use case: Workaround for classloader bug documented at https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8022063 – pojo-guy Jan 15 '19 at 17:19
  • @mcfinnigan if you want to verify that your classes can be loaded (=not broken) at build time (as opposed to run time). – Dev Null Dec 04 '19 at 00:51

3 Answers3

2

The class loader will load a .class file as soon as it's needed. If it's not needed, it won't be loaded.

Why do you think that your approach will be an improvement over what the class loader already does?

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • "The class loader will load a .class file as soon as it's needed". Thanks for the info. – julien Sep 27 '11 at 15:41
  • 3
    Another great case where answering the literal question is not a good idea (+1) – Sean Patrick Floyd Sep 27 '11 at 16:01
  • 7
    Answering the question would have been a lot more helpful. It's a perfectly valid approach, for instance, when loading a lot of user-created plugins at startup. – Nim Dec 17 '12 at 08:57
  • It is a workaround for https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8022063 – pojo-guy Jan 15 '19 at 17:17
0

You will have to open it as zip file, go through the names, assume all entries ending in .class are class files and load them, ignoring nested classes and such.

But....why?

Miserable Variable
  • 28,432
  • 15
  • 72
  • 133
-1

If you really want to read classes dynamically, leave that to the pros, who already implemented that. Implementing your own classloader is hard. Believe me. I already tried a few times. Use something like OSGi instead, which provides you dynamic class loading and much more.

Akira
  • 4,001
  • 1
  • 16
  • 24