Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all classes with Javassist using a pattern

Tags:

java

javassist

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

i found only 2 methods :

1/ Find a class by full name

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

2/ Find a list of classes with fullnames :

CtClass[] ClassPool.getDefault().get(String [] arg0)
like image 613
user1335838 Avatar asked Jun 12 '15 08:06

user1335838


2 Answers

You could use some library like : https://github.com/ronmamo/reflections

I don't think you can do that just with JRE classes.

Example from the doc :

Reflections reflections = new Reflections("my.project.prefix");

Set<Class<? extends SomeType>> subTypes = 
           reflections.getSubTypesOf(SomeType.class);

Set<Class<?>> annotated = 
           reflections.getTypesAnnotatedWith(SomeAnnotation.class);
like image 137
Michael Laffargue Avatar answered Nov 16 '22 07:11

Michael Laffargue


Michael Laffargue's suggestion is the best way to go. The Reflections library uses javassist under the covers. Basically, javassist provides a means of reading raw byte code from class or jar files and extracting the class meta-data from it without actually class loading it, where as Reflections provides a richer API around locating (via classpath specifications) and filtering the set of classes you're looking for.

You can do the same thing yourself using javassist only, but you will be recreating some portion of the Reflections library. You could look at Reflections' source code to see how it works, but very generally speaking, it looks like this:

  1. Locate the classpath you want to scan. This will usually be a group of directories with a tree of class files, or a group of Jar files, but could also include more complex structures like WARs or EARs (which Reflections supports quite nicely).

  2. Add the root of the file system where the class files live, or the JAR file reference to your ClassPool instance.

  3. Using a file system iteration or a JarInputStream, iterate through each class file or JarEntry. You can filter out any files or entries that do not match "com/stackoverflow/**.class"
  4. For the remaining, using the name of the file or entry, derrive the class name and load it from the javassist class pool.
  5. Use the loaded CtClass to apply any further search criteria.
  6. Now you have your class reference list, release the ClassPool for garbage collection.
like image 24
Nicholas Avatar answered Nov 16 '22 06:11

Nicholas