I'm writing a plugin loader -- it loads jars that are not on the classpath. I wrote a simple custom ClassLoader that takes a JarFile in its constructor and looks in the JarFile for the named class. This loader simply overrides the findClass() method of ClassLoader, and works fine.
Then I determined that I also needed to be able to get resources from the plugin jar. So I overrode findResource(). This had the unexpected result of causing the base plugin class to not be able to find other classes in the jar: I get NoClassDefFoundErrors!
In other words, if I have plugin.jar that contains MyPlugin and MyPluginComponent:
if I do not override findResource(), then I can load the jar, create an instance of MyPlugin, and that in turn can create a MyPluginComponent. However I cannot find resources that are bundled in the jar.
if I do override findResource(), then I can load the jar, create an instance of MyPlugin, but if MyPlugin attempts to create a MyPluginComponent, I get a NoClassDefFoundError.
This suggests that somehow the implementation of findResource() is unable to find class files -- but it's not even getting called (per my logging), so I don't see how that could be the case. How does this interaction work out, and how do I fix it?
I tried to write a small self-contained example, and ran into difficulty manually generating a jar file that wouldn't produce "incompatible magic number" errors. Hopefully whatever I'm doing wrong will be evident from the class loader alone. Sorry for the inconvenience, and thank you for your time.
import com.google.common.io.CharStreams;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.ClassLoader;
import java.net.URL;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Custom class loader for loading plugin classes. Adapted from
* http://kalanir.blogspot.com/2010/01/how-to-write-custom-class-loader-to.html
*/
public static class PluginLoader extends ClassLoader {
private JarFile jarFile_;
public PluginLoader(JarFile jarFile) {
super(Thread.currentThread().getContextClassLoader());
jarFile_ = jarFile;
}
#Override
public Class findClass(String className) {
try {
// Replace "." with "/" for seeking through the jar.
String classPath = className.replace(".", "/") + ".class";
System.out.println("Searching for " + className + " under " + classPath);
JarEntry entry = jarFile_.getJarEntry(classPath);
if (entry == null) {
return null;
}
InputStream stream = jarFile_.getInputStream(entry);
String contents = CharStreams.toString(
new InputStreamReader(stream));
stream.close();
byte[] bytes = contents.getBytes();
Class result = defineClass(className, bytes, 0, bytes.length);
return result;
}
catch (IOException e) {
System.out.println(e + "Unable to load jar file " + jarFile_.getName());
}
catch (ClassFormatError e) {
System.out.println(e + "Unable to read class data for class " + className + " from jar " + jarFile_.getName());
}
return null;
}
#Override
protected URL findResource(String name) {
System.out.println("Asked to find resource at " + name);
try {
String base = new File(jarFile_.getName()).toURI().toURL().toString();
URL result = new URL(String.format("jar:%s!/%s", base, name));
System.out.println("Result is " + result);
return result;
}
catch (IOException e) {
System.out.println(e + "Unable to construct URL to find " + name);
return null;
}
}
#Override
public InputStream getResourceAsStream(String name) {
System.out.println("Getting resource at " +name);
JarEntry entry = jarFile_.getJarEntry(name);
if (entry == null) {
System.out.println("Couldn't find resource " + name);
return null;
}
try {
return jarFile_.getInputStream(entry);
}
catch (IOException e) {
System.out.println(e + "Unable to load resource " + name + " from jar file " + jarFile_.getName());
return null;
}
}
}
If your requirement is to just read extra JAR files extending URLClassLoader might be a better option.
public class PluginLoader extends URLClassLoader {
public PluginLoader(String jar) throws MalformedURLException {
super(new URL[] { new File(jar).toURI().toURL() });
}
}
Related
I am using JUL in my application. Normally, Netbeans opens an output tab that reads "Tomcat" and shows the logs I produce. It was working fine. But suddenly, I realise that my logs are not shown at all, only the System.out get printed. Not even the higuest LOG.log(Level.SEVERE, ".....
} catch(Exception e) {
System.out.println("This gets printed in Netbeans tab");
LOG.log(Level.SEVERE, "This doesnt");
}
I suspect it can be a library I included, which is messing with my logs. Is that possible at all? Can a librray change the way my logs are shown? How can I investigate this, since I am a bit lost?
I suspect it can be a library I included, which is messing with my logs. Is that possible at all?
Yes. The JUL to SLF4J Bridge can remove the console handler from the JUL root logger. Some libraries invoke LogManager.reset which can remove and close all handlers.
Can a library change the way my logs are shown?
Yes. Once the a log bridge is installed the JUL records are no longer formatted by the JUL formatters.
How can I investigate this, since I am a bit lost?
Modifying the logger tree requires permissions so you can install a SecurityManager with all permissions but then turn on debug tracing with -Djava.security.debug="access,stack" to determine the caller that is modifying the logger tree.
If that doesn't work you can use good ole' System.out to print the logger tree and the attached handlers before and after a library is loaded. Then start adding an removing libraries until you see the logger change.
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class DebugLogging {
private static final Logger log = Logger.getLogger("test");
public static void main(String[] a) {
log.log(Level.FINEST, "Finest");
log.log(Level.FINER, "FINER");
log.log(Level.FINE, "FINE");
log.log(Level.CONFIG, "CONFIG");
log.log(Level.INFO, "INFO");
log.log(Level.WARNING, "WARNING");
log.log(Level.SEVERE, "SEVERE");
log.finest("Finest Log");
log.finer("Finer Log");
log.fine("Fine Log");
log.config("Config Log");
log.info("Info Log");
log.warning("Warning Log");
log.severe("Severe Log");
printConfig(System.err);
}
private static void printConfig(PrintStream ps) {
String cname = System.getProperty("java.util.logging.config.class");
if (cname != null) {
try {
ClassLoader sys = ClassLoader.getSystemClassLoader();
Class<?> c = Class.forName(cname, false, sys);
ps.println(sys.getClass().getName() +" found log configuration class " + c.getName());
} catch (LinkageError | ClassNotFoundException | RuntimeException cnfe) {
ps.println("Unable to load " + cname);
cnfe.printStackTrace(ps);
}
} else {
ps.println("java.util.logging.config.class was null");
}
String file = System.getProperty("java.util.logging.config.file");
if (file != null) {
ps.println("java.util.logging.config.file=" + file);
try {
ps.println("CanonicalPath=" + new File(file).getCanonicalPath());
} catch (RuntimeException | IOException ioe) {
ps.println("Unable to resolve path for " + file);
ioe.printStackTrace(ps);
}
try {
Path p = Paths.get(file);
if (Files.isReadable(p)) {
ps.println(file + " is readable and has size " + Files.size(p));
} else {
if (Files.exists(p)) {
ps.println(file + " exists for " + System.getProperty("user.name") + " but is not readable.");
} else {
ps.println(file + " doesn't exist for " + System.getProperty("user.name"));
}
}
} catch (RuntimeException | IOException ioe) {
ps.println("Unable to read " + file);
ioe.printStackTrace(ps);
}
} else {
ps.println("java.util.logging.config.file was null");
}
LogManager lm = LogManager.getLogManager();
ps.append("LogManager=").println(lm.getClass().getName());
synchronized (lm) {
Enumeration<String> e = lm.getLoggerNames();
while (e.hasMoreElements()) {
Logger l = lm.getLogger(e.nextElement());
if (l != null) {
print(l, ps);
}
}
}
}
private static void print(Logger l, PrintStream ps) {
String scn = l.getClass().getSimpleName();
ps.append("scn=").append(scn).append(", n=").append(l.getName())
.append(", uph=").append(String.valueOf(l.getUseParentHandlers()))
.append(", l=").append(String.valueOf(l.getLevel()))
.append(", fl=").println(l.getFilter());
for (Handler h : l.getHandlers()) {
ps.append("\t").append(l.getName()).append("->")
.append(h.getClass().getName()).append(", h=")
.append(String.valueOf(h.getLevel())).append(", fl=")
.append(String.valueOf(h.getFilter())).println();
}
}
}
I am trying to make a Java tool that will scan the structure of a Java application and provide some meaningful information. To do this, I need to be able to scan all of the .class files from the project location (JAR/WAR or just a folder) and use reflection to read about their methods. This is proving to be near impossible.
I can find a lot of solutions based on URLClassloader that allow me to load specific classes from a directory/archive, but none that will allow me to load classes without having any information about the class name or package structure.
EDIT:
I think I phrased this poorly. My issue is not that I can't get all of the class files, I can do that with recursion etc. and locate them properly. My issue is obtaining a Class object for each class file.
The following code loads all classes from a JAR file. It does not need to know anything about the classes. The names of the classes are extracted from the JarEntry.
JarFile jarFile = new JarFile(pathToJar);
Enumeration<JarEntry> e = jarFile.entries();
URL[] urls = { new URL("jar:file:" + pathToJar+"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
if(je.isDirectory() || !je.getName().endsWith(".class")){
continue;
}
// -6 because of .class
String className = je.getName().substring(0,je.getName().length()-6);
className = className.replace('/', '.');
Class c = cl.loadClass(className);
}
edit:
As suggested in the comments above, javassist would also be a possibility.
Initialize a ClassPool somewhere before the while loop form the code above, and instead of loading the class with the class loader, you could create a CtClass object:
ClassPool cp = ClassPool.getDefault();
...
CtClass ctClass = cp.get(className);
From the ctClass, you can get all methods, fields, nested classes, ....
Take a look at the javassist api:
https://jboss-javassist.github.io/javassist/html/index.html
List All the classes inside jar file.
public static List getClasseNames(String jarName) {
ArrayList classes = new ArrayList();
if (debug)
System.out.println("Jar " + jarName );
try {
JarInputStream jarFile = new JarInputStream(new FileInputStream(
jarName));
JarEntry jarEntry;
while (true) {
jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null) {
break;
}
if (jarEntry.getName().endsWith(".class")) {
if (debug)
System.out.println("Found "
+ jarEntry.getName().replaceAll("/", "\\."));
classes.add(jarEntry.getName().replaceAll("/", "\\."));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return classes;
}
To do this, I need to be able to scan all of the .class files from the project location (JAR/WAR or just a folder)
Scanning all of the files in a folder is simple. One option is to call File.listFiles() on the File that denotes the folder, then iterate the resulting array. To traverse trees of nested folders, use recursion.
Scanning the files of a JAR file can be done using the JarFile API ... and you don't need to recurse to traverse nested "folders".
Neither of these is particularly complicated. Just read the javadoc and start coding.
Came here with similar requirements:
Have a developing number of service classes in some package, which implement a common
interface, and want to detect them at run time.
Partial problem is finding classes inside a specific package, where the application may be loaded from a jar file or from unpacked classes in a package/folder structure.
So I put the solutions from amicngh and an anonymous together.
// Retrieve classes of a package and it's nested package from file based class repository
package esc;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
public class GetClasses
{
private static boolean debug = false;
/**
* test function with assumed package esc.util
*/
public static void main(String... args)
{
try
{
final Class<?>[] list = getClasses("esc.util");
for (final Class<?> c : list)
{
System.out.println(c.getName());
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* #precondition Thread Class loader attracts class and jar files, exclusively
* #precondition Classes with static code sections are executed, when loaded and thus must not throw exceptions
*
* #param packageName
* [in] The base package path, dot-separated
*
* #return The classes of package /packageName/ and nested packages
*
* #throws IOException,
* ClassNotFoundException not applicable
*
* #author Sam Ginrich, http://www.java2s.com/example/java/reflection/recursive-method-used-to-find-all-classes-in-a-given-directory-and-sub.html
*
*/
public static Class<?>[] getClasses(String packageName) throws IOException
{
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
if (debug)
{
System.out.println("Class Loader class is " + classLoader.getClass().getName());
}
final String packagePath = packageName.replace('.', '/');
final Enumeration<URL> resources = classLoader.getResources(packagePath);
final List<Class<?>> classes = new ArrayList<Class<?>>();
while (resources.hasMoreElements())
{
final URL resource = resources.nextElement();
final String proto = resource.getProtocol();
if ("file".equals(proto))
{
classes.addAll(findFileClasses(new File(resource.getFile()), packageName));
}
else if ("jar".equals(proto))
{
classes.addAll(findJarClasses(resource));
}
else
{
System.err.println("Protocol " + proto + " not supported");
continue;
}
}
return classes.toArray(new Class[classes.size()]);
}
/**
* Linear search for classes of a package from a jar file
*
* #param packageResource
* [in] Jar URL of the base package, i.e. file URL bested in jar URL
*
* #return The classes of package /packageResource/ and nested packages
*
* #throws -
*
* #author amicngh, Sam Ginrich#stackoverflow.com
*/
private static List<Class<?>> findJarClasses(URL packageResource)
{
final List<Class<?>> classes = new ArrayList<Class<?>>();
try
{
System.out.println("Jar URL Path is " + packageResource.getPath());
final URL fileUrl = new URL(packageResource.getPath());
final String proto = fileUrl.getProtocol();
if ("file".equals(proto))
{
final String filePath = fileUrl.getPath().substring(1); // skip leading /
final int jarTagPos = filePath.indexOf(".jar!/");
if (jarTagPos < 0)
{
System.err.println("Non-conformant jar file reference " + filePath + " !");
}
else
{
final String packagePath = filePath.substring(jarTagPos + 6);
final String jarFilename = filePath.substring(0, jarTagPos + 4);
if (debug)
{
System.out.println("Package " + packagePath);
System.out.println("Jar file " + jarFilename);
}
final String packagePrefix = packagePath + '/';
try
{
final JarInputStream jarFile = new JarInputStream(
new FileInputStream(jarFilename));
JarEntry jarEntry;
while (true)
{
jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null)
{
break;
}
final String classPath = jarEntry.getName();
if (classPath.startsWith(packagePrefix) && classPath.endsWith(".class"))
{
final String className = classPath
.substring(0, classPath.length() - 6).replace('/', '.');
if (debug)
{
System.out.println("Found entry " + jarEntry.getName());
}
try
{
classes.add(Class.forName(className));
}
catch (final ClassNotFoundException x)
{
System.err.println("Cannot load class " + className);
}
}
}
jarFile.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}
else
{
System.err.println("Nested protocol " + proto + " not supprted!");
}
}
catch (final MalformedURLException e)
{
e.printStackTrace();
}
return classes;
}
/**
* Recursive method used to find all classes in a given directory and subdirs.
*
* #param directory
* The base directory
* #param packageName
* The package name for classes found inside the base directory
* #return The classes
* #author http://www.java2s.com/example/java/reflection/recursive-method-used-to-find-all-classes-in-a-given-directory-and-sub.html
* #throws -
*
*/
private static List<Class<?>> findFileClasses(File directory, String packageName)
{
final List<Class<?>> classes = new ArrayList<Class<?>>();
if (!directory.exists())
{
System.err.println("Directory " + directory.getAbsolutePath() + " does not exist.");
return classes;
}
final File[] files = directory.listFiles();
if (debug)
{
System.out.println("Directory "
+ directory.getAbsolutePath()
+ " has "
+ files.length
+ " elements.");
}
for (final File file : files)
{
if (file.isDirectory())
{
assert !file.getName().contains(".");
classes.addAll(findFileClasses(file, packageName + "." + file.getName()));
}
else if (file.getName().endsWith(".class"))
{
final String className = packageName
+ '.'
+ file.getName().substring(0, file.getName().length() - 6);
try
{
classes.add(Class.forName(className));
}
catch (final ClassNotFoundException cnf)
{
System.err.println("Cannot load class " + className);
}
}
}
return classes;
}
}
I have a Jar in java which is containing 2 classes and 1 Interface. How can i get the interface and class names from the jar. Currently I am able to get the class names, but not the interface name.
List jClasses = getClasseNames("D://Test.jar");
System.out.println(jClasses.size());
for (int i = 0; i < jClasses.size(); i++) {
System.out.println("Print Classes ::" + jClasses.get(i));
if(( null != jClasses.getClass().getInterfaces()[i])) {
System.out.println(jClasses.getClass().getInterfaces()[i]);
} else {
System.out.println("No connection");
}
}
public static List getClasseNames(String jarName) {
ArrayList classes = new ArrayList();
try {
JarInputStream jarFile = new JarInputStream(new FileInputStream(
jarName));
JarEntry jarEntry;
while (true) {
jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null) {
break;
}
if (jarEntry.getName().endsWith(".class")) {
classes.add(jarEntry.getName().replaceAll("/", "\\."));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return classes;
}
output :
Print Classes ::com.java.testclient.PTest1.class
interface java.util.List
======
Print Classes ::com.java.testclient.ClassSpy.class
interface java.util.RandomAccess
======
Print Classes ::com.java.testclient.myInt.class
interface java.lang.Cloneable
======
Print Classes ::com.java.testclient.PTest.class
interface java.io.Serializable
Please suggest.
You can use this class:
package io.github.gabrielbb.java.utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
/**
* #author Gabriel Basilio Brito
* #since 12/26/2016
* #version 1.1
*/
public class ClassesAndInterfacesFromJar {
public static List<Class> getJarClasses(String jarPath) throws IOException, ClassNotFoundException {
File jarFile = new File(jarPath);
return getJarClasses(jarFile);
}
public static List<Class> getJarClasses(File jar) throws IOException, ClassNotFoundException {
ArrayList<Class> classes = new ArrayList();
JarInputStream jarInputStream = null;
URLClassLoader cl;
try {
cl = URLClassLoader.newInstance(new URL[]{new URL("jar:file:" + jar + "!/")}); // To load classes inside the jar, after getting their names
jarInputStream = new JarInputStream(new FileInputStream(
jar)); // Getting a JarInputStream to iterate through the Jar files
JarEntry jarEntry = jarInputStream.getNextJarEntry();
while (jarEntry != null) {
if (jarEntry.getName().endsWith(".class")) { // Avoiding non ".class" files
String className = jarEntry.getName().replaceAll("/", "\\."); // The ClassLoader works with "." instead of "/"
className = className.substring(0, jarEntry.getName().length() - 6); // Removing ".class" from the string
Class clazz = cl.loadClass(className); // Loading the class by its name
classes.add(clazz);
}
jarEntry = jarInputStream.getNextJarEntry(); // Next File
}
} finally {
if (jarInputStream != null) {
jarInputStream.close(); // Closes the FileInputStream
}
}
return classes;
}
// Main Method for testing purposes
public static void main(String[] args) {
try {
String jarPath = "C://Test.jar";
List<Class> classes = getJarClasses(jarPath);
for (Class c : classes) {
// Here we can use the "isInterface" method to differentiate an Interface from a Class
System.out.println(c.isInterface() ? "Interface: " + c.getName() : "Class: " + c.getName());
}
} catch (Exception ex) {
System.err.println(ex);
}
}
It can be found at:
https://github.com/GabrielBB/Java-Utilities/blob/master/ClassesAndInterfacesFromJar.java
I wrote my classloader:
package ru.sberbank.school.homework8;
import ru.sberbank.school.homework8.plugin.Plugin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class PluginManager extends ClassLoader {
private final String pluginRootDirectory;
public PluginManager(String pluginRootDirectory) {
this.pluginRootDirectory = pluginRootDirectory;
}
public Plugin load(String pluginName, String pluginClassName) {
String name = pluginName + "." + pluginClassName;
try {
Class clazz;
try {
clazz = super.findSystemClass(name);
} catch (ClassNotFoundException e) {
String fileName = pluginRootDirectory + "\\" + pluginName + "\\" + pluginClassName + ".class";
try (FileInputStream fin = new FileInputStream(fileName)) {
byte[] buffer = new byte[(int) (new File(fileName).length())];
fin.read(buffer);
clazz = defineClass(name, buffer, 0, buffer.length);
}
}
return (Plugin)clazz.newInstance();
} catch (IOException | InstantiationException | IllegalAccessException ignored) {
return null;
}
}
}
When I run it:
package ru.sberbank.school.homework8;
import ru.sberbank.school.homework8.plugin.Plugin;
public class PluginManagerTest {
public static void main(String[] args) {
String pluginRootDirectory = "D:\\sbt\\target\\classes\\ru\\sberbank\\school\\homework8";
PluginManager pluginManager = new PluginManager(pluginRootDirectory);
Plugin plugin = pluginManager.load("plugin", "PluginImpl");
if (plugin != null) {
plugin.doUseful();
}
}
}
Exception in thread "main" java.lang.NoClassDefFoundError:
plugin/PluginImpl (wrong name:
ru/sberbank/school/homework8/plugin/PluginImpl) at
java.lang.ClassLoader.defineClass1(Native Method)
I get NoClassDefFoundError. Why??? How can I fix it???
Help me, please!
package ru.sberbank.school.homework8.plugin;
public class PluginImpl implements Plugin {
#Override
public void doUseful() {
System.out.println("My plugin!");
}
}
You get this error because you don't provide the correct FQN of your class, indeed in your load method, you try to find the class corresponding to pluginName + "." + pluginClassName that will be in your case plugin.PluginImpl but the package name of your class PluginImpl is actually ru.sberbank.school.homework8.plugin such that the real FQN of your class is ru.sberbank.school.homework8.plugin.PluginImpl.
To fix this problem, you need to replace:
Plugin plugin = pluginManager.load("plugin", "PluginImpl");
With:
Plugin plugin = pluginManager.load("ru.sberbank.school.homework8.plugin", "PluginImpl");
Or you could modify your method load to add a prefix assuming that you will always retrieve your plugins from the same root package:
public Plugin load(String pluginName, String pluginClassName) {
String name = "ru.sberbank.school.homework8." + pluginName + "." + pluginClassName;
I am trying to make a Java tool that will scan the structure of a Java application and provide some meaningful information. To do this, I need to be able to scan all of the .class files from the project location (JAR/WAR or just a folder) and use reflection to read about their methods. This is proving to be near impossible.
I can find a lot of solutions based on URLClassloader that allow me to load specific classes from a directory/archive, but none that will allow me to load classes without having any information about the class name or package structure.
EDIT:
I think I phrased this poorly. My issue is not that I can't get all of the class files, I can do that with recursion etc. and locate them properly. My issue is obtaining a Class object for each class file.
The following code loads all classes from a JAR file. It does not need to know anything about the classes. The names of the classes are extracted from the JarEntry.
JarFile jarFile = new JarFile(pathToJar);
Enumeration<JarEntry> e = jarFile.entries();
URL[] urls = { new URL("jar:file:" + pathToJar+"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
if(je.isDirectory() || !je.getName().endsWith(".class")){
continue;
}
// -6 because of .class
String className = je.getName().substring(0,je.getName().length()-6);
className = className.replace('/', '.');
Class c = cl.loadClass(className);
}
edit:
As suggested in the comments above, javassist would also be a possibility.
Initialize a ClassPool somewhere before the while loop form the code above, and instead of loading the class with the class loader, you could create a CtClass object:
ClassPool cp = ClassPool.getDefault();
...
CtClass ctClass = cp.get(className);
From the ctClass, you can get all methods, fields, nested classes, ....
Take a look at the javassist api:
https://jboss-javassist.github.io/javassist/html/index.html
List All the classes inside jar file.
public static List getClasseNames(String jarName) {
ArrayList classes = new ArrayList();
if (debug)
System.out.println("Jar " + jarName );
try {
JarInputStream jarFile = new JarInputStream(new FileInputStream(
jarName));
JarEntry jarEntry;
while (true) {
jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null) {
break;
}
if (jarEntry.getName().endsWith(".class")) {
if (debug)
System.out.println("Found "
+ jarEntry.getName().replaceAll("/", "\\."));
classes.add(jarEntry.getName().replaceAll("/", "\\."));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return classes;
}
To do this, I need to be able to scan all of the .class files from the project location (JAR/WAR or just a folder)
Scanning all of the files in a folder is simple. One option is to call File.listFiles() on the File that denotes the folder, then iterate the resulting array. To traverse trees of nested folders, use recursion.
Scanning the files of a JAR file can be done using the JarFile API ... and you don't need to recurse to traverse nested "folders".
Neither of these is particularly complicated. Just read the javadoc and start coding.
Came here with similar requirements:
Have a developing number of service classes in some package, which implement a common
interface, and want to detect them at run time.
Partial problem is finding classes inside a specific package, where the application may be loaded from a jar file or from unpacked classes in a package/folder structure.
So I put the solutions from amicngh and an anonymous together.
// Retrieve classes of a package and it's nested package from file based class repository
package esc;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
public class GetClasses
{
private static boolean debug = false;
/**
* test function with assumed package esc.util
*/
public static void main(String... args)
{
try
{
final Class<?>[] list = getClasses("esc.util");
for (final Class<?> c : list)
{
System.out.println(c.getName());
}
}
catch (final IOException e)
{
e.printStackTrace();
}
}
/**
* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
*
* #precondition Thread Class loader attracts class and jar files, exclusively
* #precondition Classes with static code sections are executed, when loaded and thus must not throw exceptions
*
* #param packageName
* [in] The base package path, dot-separated
*
* #return The classes of package /packageName/ and nested packages
*
* #throws IOException,
* ClassNotFoundException not applicable
*
* #author Sam Ginrich, http://www.java2s.com/example/java/reflection/recursive-method-used-to-find-all-classes-in-a-given-directory-and-sub.html
*
*/
public static Class<?>[] getClasses(String packageName) throws IOException
{
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
if (debug)
{
System.out.println("Class Loader class is " + classLoader.getClass().getName());
}
final String packagePath = packageName.replace('.', '/');
final Enumeration<URL> resources = classLoader.getResources(packagePath);
final List<Class<?>> classes = new ArrayList<Class<?>>();
while (resources.hasMoreElements())
{
final URL resource = resources.nextElement();
final String proto = resource.getProtocol();
if ("file".equals(proto))
{
classes.addAll(findFileClasses(new File(resource.getFile()), packageName));
}
else if ("jar".equals(proto))
{
classes.addAll(findJarClasses(resource));
}
else
{
System.err.println("Protocol " + proto + " not supported");
continue;
}
}
return classes.toArray(new Class[classes.size()]);
}
/**
* Linear search for classes of a package from a jar file
*
* #param packageResource
* [in] Jar URL of the base package, i.e. file URL bested in jar URL
*
* #return The classes of package /packageResource/ and nested packages
*
* #throws -
*
* #author amicngh, Sam Ginrich#stackoverflow.com
*/
private static List<Class<?>> findJarClasses(URL packageResource)
{
final List<Class<?>> classes = new ArrayList<Class<?>>();
try
{
System.out.println("Jar URL Path is " + packageResource.getPath());
final URL fileUrl = new URL(packageResource.getPath());
final String proto = fileUrl.getProtocol();
if ("file".equals(proto))
{
final String filePath = fileUrl.getPath().substring(1); // skip leading /
final int jarTagPos = filePath.indexOf(".jar!/");
if (jarTagPos < 0)
{
System.err.println("Non-conformant jar file reference " + filePath + " !");
}
else
{
final String packagePath = filePath.substring(jarTagPos + 6);
final String jarFilename = filePath.substring(0, jarTagPos + 4);
if (debug)
{
System.out.println("Package " + packagePath);
System.out.println("Jar file " + jarFilename);
}
final String packagePrefix = packagePath + '/';
try
{
final JarInputStream jarFile = new JarInputStream(
new FileInputStream(jarFilename));
JarEntry jarEntry;
while (true)
{
jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null)
{
break;
}
final String classPath = jarEntry.getName();
if (classPath.startsWith(packagePrefix) && classPath.endsWith(".class"))
{
final String className = classPath
.substring(0, classPath.length() - 6).replace('/', '.');
if (debug)
{
System.out.println("Found entry " + jarEntry.getName());
}
try
{
classes.add(Class.forName(className));
}
catch (final ClassNotFoundException x)
{
System.err.println("Cannot load class " + className);
}
}
}
jarFile.close();
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}
else
{
System.err.println("Nested protocol " + proto + " not supprted!");
}
}
catch (final MalformedURLException e)
{
e.printStackTrace();
}
return classes;
}
/**
* Recursive method used to find all classes in a given directory and subdirs.
*
* #param directory
* The base directory
* #param packageName
* The package name for classes found inside the base directory
* #return The classes
* #author http://www.java2s.com/example/java/reflection/recursive-method-used-to-find-all-classes-in-a-given-directory-and-sub.html
* #throws -
*
*/
private static List<Class<?>> findFileClasses(File directory, String packageName)
{
final List<Class<?>> classes = new ArrayList<Class<?>>();
if (!directory.exists())
{
System.err.println("Directory " + directory.getAbsolutePath() + " does not exist.");
return classes;
}
final File[] files = directory.listFiles();
if (debug)
{
System.out.println("Directory "
+ directory.getAbsolutePath()
+ " has "
+ files.length
+ " elements.");
}
for (final File file : files)
{
if (file.isDirectory())
{
assert !file.getName().contains(".");
classes.addAll(findFileClasses(file, packageName + "." + file.getName()));
}
else if (file.getName().endsWith(".class"))
{
final String className = packageName
+ '.'
+ file.getName().substring(0, file.getName().length() - 6);
try
{
classes.add(Class.forName(className));
}
catch (final ClassNotFoundException cnf)
{
System.err.println("Cannot load class " + className);
}
}
}
return classes;
}
}