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
Its not recommended, but you can put your class in the default package, too.
To know the ClassLoader that loads a class the getClassLoader() method is used. All classes are loaded based on their names and if any of these classes are not found then it returns a NoClassDefFoundError or ClassNotFoundException.
No. Even if you just create a Java file without any package name and compile it, the resulting class file will have a package name (.) which is also known as defaultpackage.
The package for a class can be obtained using the java. lang. Class. getPackage() method with the help of the class loader of the class.
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).
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.
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.
Class.forName(new Reflections("com.xyz", new SubTypesScanner(false)).getAllTypes().stream()
.filter(o -> o.endsWith(".Foo"))
.findFirst()
.orElse(null));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With