Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find loaded class with a specific annotation

I'm writing a custom, cross-platform serialization method which supports custom types (standard types being strings, numbers, maps, lists, etc.) by annotating a class like this:

@CompactTypeName("myapp.BetweenFilter")
public static class BetweenFilter implements NumericFilter {

    static {
        CompactSerializer.registerClass(BetweenFilter.class);
    }

    ...

    @SuppressWarnings("unused")
    @Deserialize
    private static BetweenFilter compactRead(DataInputStream ins) throws IOException {
        return new BetweenFilter(ins.readInt(), ins.readInt());
    }

    @SuppressWarnings("unused")
    @Serialize
    private void compactWrite(DataOutputStream ous) throws IOException {
        ous.writeInt(from);
        ous.writeInt(to);
    }

}

The problem is that the static initializer there creates a runtime dependency on the serialization component, which the other parts don't (annotations not present at runtime are ignored).

To solve this, instead of the class registering itself with the CompactSerializer, the serializer should have some way of find the class and associating it with the given type name ("myapp.BetweenFilter").

How can I do that? I know it's possible, since Spring-MVC, for example, can automatically find classes with @Controller.

like image 618
Bart van Heukelom Avatar asked Dec 11 '25 18:12

Bart van Heukelom


1 Answers

You need to scan the classpath. Basically: you'll have to

  • find every classpath element (folder or Jar)
  • traverse each element to find all items named *.class (by walking either the file system or the jar entries)
  • load the classes
  • check them for annotations (if you look for method annotations, scan all methods of all classes on your classpath)

Spring has highly specialized classes to do all of this. You can write this functionality from scratch, but it is a huge pain.

like image 167
Sean Patrick Floyd Avatar answered Dec 14 '25 08:12

Sean Patrick Floyd