Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load class without knowing package?

Tags:

java

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

like image 767
user291701 Avatar asked Sep 30 '11 20:09

user291701


People also ask

Can we create class without package?

Its not recommended, but you can put your class in the default package, too.

How do I know what ClassLoader loads a class?

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.

Can a Java class be without package?

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.

How do I get packages from class?

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.


4 Answers

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).

like image 51
maerics Avatar answered Oct 14 '22 00:10

maerics


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.

like image 42
Michael Borgwardt Avatar answered Oct 14 '22 00:10

Michael Borgwardt


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.

like image 43
millimoose Avatar answered Oct 14 '22 00:10

millimoose


Using java Reflections:

Class.forName(new Reflections("com.xyz", new SubTypesScanner(false)).getAllTypes().stream()
    .filter(o -> o.endsWith(".Foo"))
    .findFirst()
    .orElse(null));

like image 40
James Smith Avatar answered Oct 13 '22 23:10

James Smith