3

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.

Bart van Heukelom
  • 43,244
  • 59
  • 186
  • 301
  • 1
    This question may be relevant: http://stackoverflow.com/questions/259140/scanning-java-annotations-at-runtime –  May 18 '11 at 14:52

2 Answers2

3

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.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
2

Look for more information about annotation processors in Java 6.

Rostislav Matl
  • 4,294
  • 4
  • 29
  • 53