Reputation: 39671
Is it possible to load a class by name if you don't know the whole package path? Something like:
getClassLoader().loadClass("Foo");
The class named "Foo" might be around, might not be - I don't know the package. I'd like to get a listing of matching classes and their packages (but not sure that's possible!),
Thanks
Upvotes: 8
Views: 7617
Reputation: 31
Class.forName(new Reflections("com.xyz", new SubTypesScanner(false)).getAllTypes().stream()
.filter(o -> o.endsWith(".Foo"))
.findFirst()
.orElse(null));
Upvotes: 1
Reputation: 39950
Contrary to the previous answers, and in addition to the answers in the question @reader_1000 linked to:
This is possible, by essentially duplicating the logic by which Java searches for classes to load, and looking at all the classfiles. Libraries are available that handle this part, I remember using Reflections. Matching classes by unqualified name isn't their major use case, but the library seems general enough and this should be doable if you poke around. Do note that this will, very likely, be a fairly slow operation.
Upvotes: 3
Reputation: 3260
Even if you don't know the package name, sites like jarFinder might know it
Upvotes: -3
Reputation: 346260
If you don't know the package, you don't know the name of a class (because it's part of the fully qualified class name) and therefore cannot find the class.
The Java class loading mechanism basically only allows you to do one thing: ask for a class with its fully qualified name, and the classloader will either return the class or nothing. That's it. There#s no way to ask for partial matches, or to list packages.
Upvotes: 3
Reputation: 156384
Nope. The Java ClassLoader.loadClass(String)
method requires that class names must be fully qualified by their package and class name (aka "Binary name" in the Java Language Specification).
Upvotes: 7