Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you find all classes in a package using reflection?

Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. Package, it would seem like no.)

like image 530
Jonik Avatar asked Feb 06 '09 13:02

Jonik


People also ask

How do I get all classes in a classpath?

You can get all classpath roots by passing an empty String into ClassLoader#getResources() . Enumeration<URL> roots = classLoader. getResources("");

How do you find the class of a reflection?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");

How can you directly access all classes in the packages in Java?

Multiple files can specify the same package name. If package name is specified, the file must be in a subdirectory called name (i.e., the directory name must match the package name). We can access public classes in another (named) package using: package-name. class-name.

Which method gets Package info using reflection?

Package Information. By using Java reflection, we are also able to get information about the package of any class or object. This data is bundled inside the Package class, which is returned by a call to getPackage method on the class object.


Video Answer


1 Answers

Due to the dynamic nature of class loaders, this is not possible. Class loaders are not required to tell the VM which classes it can provide, instead they are just handed requests for classes, and have to return a class or throw an exception.

However, if you write your own class loaders, or examine the classpaths and it's jars, it's possible to find this information. This will be via filesystem operations though, and not reflection. There might even be libraries that can help you do this.

If there are classes that get generated, or delivered remotely, you will not be able to discover those classes.

The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming.

Addendum: The Reflections Library will allow you to look up classes in the current classpath. It can be used to get all classes in a package:

 Reflections reflections = new Reflections("my.project.prefix");   Set<Class<? extends Object>> allClasses =       reflections.getSubTypesOf(Object.class); 
like image 82
Staale Avatar answered Oct 27 '22 13:10

Staale