One of the things that every Spring and EJB3 developer does on a daily basis is to use annotations to inject instance variables into your objects, which, it seems, has become something we do without thinking about.

You know the type of thing I’m talking about: you write a couple of classes annotating one with @Component and the other with @Autowired and when you run your killer app hey presto everything’s happily glued together.

Now, this blog isn’t going to show you how to build a fully functional factory for loading classes using dependency injection and and annotations. It will, however, take a peak behind the magic and demonstrate some of the techniques that may have been employed by the Guys at Spring and the EJB3 Team.

Let’s consider for one moment... if you were writing a fully functional factory for loading classes, then what kinds of tasks would you need to accomplish? The first one I can think of is, given some kind of starting point, being able to walk through all the classes on the class-path figuring out which ones are marked with our annotations. This should include classes both on the file system as .class files and those stuck inside JAR files. Secondly, when testing for annotations, you’ll need to check both class level, method level, and field level attributes in order to auto-wire the bits together. Lastly, you need to instantiate the classes and do the auto-wiring, whilst getting around any accessibility problems... all of which is too much t put into one blog.

Today’s blog covers step one, and will demonstrate how to traverse a package structure from a known starting point. The starting point will be a package name, which is no surprise as that the way Spring does it with the following configuration file entry:

<mvc:annotation-driven />

Sample below ignores any annotations for one moment and merely creates a list of Class objects, which are then displayed on the screen with a simple System.out.println(...).

Note that in this sample, I’m also ignoring classes that are located in JAR files. Accessing those is fairly similar, you just need to use the JarFile class, but more on that later perhaps...

The getClasses(...) method is the starting point of this class. Firstly, it gets hold of the directory containing our classes using getPackageDirectory(...) and then uses a spot of recursion, with findClasses(...) calling findClasses(...) every time it finds a new directory. Each call to the this method returns a list of classes, which is then added to the preceding list... and that’s the simple case covered. My next blog covers extracting classes from a JAR file.