julien
julien

Reputation: 958

How to load all classes of a jar file at runtime?

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?

Upvotes: 1

Views: 6021

Answers (3)

Akira
Akira

Reputation: 4071

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.

Upvotes: -1

duffymo
duffymo

Reputation: 308753

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?

Upvotes: 2

Miserable Variable
Miserable Variable

Reputation: 28752

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?

Upvotes: 0

Related Questions