Getting all classes using Javassist using template

How can I get all classes using a template like "com.stackoverflow. *" With Javassist?

I found only 2 methods:

1 / Find a class by name

CtClass ClassPool.getDefault().getCtClass("com.stackoverflow.user.name") 

2 / Find the list of classes with full names:

 CtClass[] ClassPool.getDefault().get(String [] arg0) 
+5
source share
2 answers

You can use some library, for example: https://github.com/ronmamo/reflections

I do not think you can only do this with JRE classes.

Example from the document:

 Reflections reflections = new Reflections("my.project.prefix"); Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class); 
+3
source

Michael Luffarg's suggestion is the best way to go. Reflections library uses javassist under covers. Basically, javassist provides a means to read the source byte code from class or jar files and extract class metadata from it without actually loading the class, when Reflections provides a richer API for locating (through class specifications) and filtering the set of classes that you are looking for.

You can do the same using only javassist, but you will recreate part of the Reflections library. You can look at the source code of Reflections to see how it works, but, in general, it looks like this:

  • Find the path to the class you want to scan. This is usually a directory group with a tree of class files or a group of Jar files, but may also include more complex structures such as WAR or EAR (which Reflections support pretty well).

  • Add the root of the file system where the class files live, or a link to the JAR file for your ClassPool instance.

  • Using file system iteration or JarInputStream, repeat each class file or JarEntry. You can filter out any files or entries that do not match "com / stackoverflow / **. Class"
  • For the rest, using the file or record name, invert the class name and load it from the javassist class pool.
  • Use the loaded CtClass to apply any other search criteria.
  • Now that you have a list of class references, release the ClassPool garbage collection.
+3
source

All Articles