How to find out package classes in java?

Possible duplicate:
Can you find all classes in a package using reflection?

Suppose I have a package name as a string:

String pkgName = "com.forat.web.servlets"; 

How to find out the types in this package?

+1
source share
4 answers

This is not possible in full generality. If your classes are stored in a directory or a JAR file, you can look at its contents, but the classloader mechanism is so flexible that the question "what classes in this package" simply does not make sense - you can write a class loader that returns a class for any class name that you are requesting.

+3
source

Can you provide more detailed information, such as which medium? A separate application, webapp on the application server. Where are the classes loaded? JAR, individual files in the file system, network class loader, etc.

There is no simple answer, simply because there is no simple package definition. The package can be distributed to several banks, loaders of several classes, and in the case of network class loaders, classes exist on another computer.

Finally, do you just want to look at the classes loaded into the virtual machine or all the classes present in the classpath?

EDIT: see also this related question.

+1
source

These two answers explain methods that should cover many practical issues:

0
source

f you have a .jar file from which you want to get .class files, you can use the following:

  • java.util.jar.JarEntry

  • java.net.JarURLConnection created using java.net.JarURLConnection java.​net.​URL .

  • The URL in this case is the package name in this case: com.forat.web.servlets

Example

(NOTE: ignores exception handling)

 // Get the "things" that are in the .jar Enumeration<JarEntry> jarEntries = ((JarURLConnection)urlToJar.openConnection()).getJarFile().entries(); while(jarEntries.hasMoreElements()) { String entry = jarEntries.nextElement().getName(); if (entry.endsWith(".class")) { // TODO: Remove "." from result. // Here is the first of the classes in the .servlets location Class.forName(entry); } } 

0
source

Source: https://habr.com/ru/post/1308582/


All Articles