0

I'd like to search a class that matches a given pattern in all the classes loaded at the current moment.

For example I'd like to do something like:

List<Class<?>> classess = getClassesFromPattern("*.Entity*");

And as a result I'd get:

com.package.EntityA
com.package.EntityB
com.package.EntityC

How would I implement that?

Jordi P.S.
  • 3,838
  • 7
  • 36
  • 59
  • 1
    *"Any idea?"* 1) Ask a ***specific*** question. 2) Show us what you tried. – Andrew Thompson May 15 '13 at 14:41
  • 3
    You can try to [get a list of all loaded classes](http://stackoverflow.com/questions/2548384/java-get-a-list-of-all-classes-loaded-in-the-jvm) then browse that list. Better link: http://stackoverflow.com/questions/2681459/how-can-i-list-all-classes-loaded-in-a-specific-class-loader – assylias May 15 '13 at 14:42

3 Answers3

1

It's easy with corn-cps

List<Class<?>> classes = CPScanner.scanClasses(new PackageNameFilter(
                "com.package"), new ClassNameFilter("*Entity*"));
Serhat
  • 222
  • 4
  • 2
0

First do Instrumentation.getInitiatedClasses(ClassLoader) (see http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html#getInitiatedClasses(java.lang.ClassLoader)) which Returns an array of all classes for which loader is an initiating loader. If the supplied loader is null, classes initiated by the bootstrap class loader are returned. Now search your pattern in result return by getInitiatedClasses method

M Sach
  • 33,416
  • 76
  • 221
  • 314
0

It is not so simple as you want.

Class.forName() retrieves one class according the fully qualified class name you specified.

You can analyze your classpath, read all class path fragments, then read classes as resources (different for jar files and plain directories) and search for the classes according to pattern.

The good news is that such library exists. It is named Reflections. It allows to get classes by various criteria including implemented interfaces, annotations and (probably) class name pattern. It is also extendable and you can add your own implementation according to your needs.

AlexR
  • 114,158
  • 16
  • 130
  • 208