Friday, December 24, 2010

Find all the classes in the same package

It's been a slow month for blogging, due to the release of a new World of Warcraft expansion, crazy year end software releases at work and the general retardation of the human collective consciousness that happens this time of year.

With all of that I did however have some fun writing the following bit of code. We have a "generic" getter and setter test utility used to ensure a couple extra %'s of code coverage with minimal effort. That utility did however requires that you call it for every class you want to test, being lazy I wanted to just give it a class from a specific package and have that check all the classes.

I initially thought there would have to be just a simple way to do it with the Java reflection API. Unfortunately I didn't find any, it seems a "Package" does not keep track of it's classes, so after a bit of digging on the net and feverish typing (ignoring the actual project I am currently working on for a little) here is what I came up with. The tip is actually the just methods from the java.lang.Class object: "getProtectionDomain().getCodeSource().getLocation().toURI()", giving you the base to work from and I found that somewhere on Stackoverflow.

There are 2 public methods: findAllClassesInSamePackage and findAllInstantiableClassesInSamePackage. (For my purposes of code coverage I just needed the instantiable classes.)




  1. I have used a custom doclet for a similar task. I think doclet is cleaner way to do this.

  2. I have never really used doclets. I'll have a look if I have some time in the next couple days, but I am quite sure there are a couple of ways of doing this. :)

  3. Well you describe it, you are absolutely right.

  4. It is the best deal for those Who wants to get classes. They can get all classes in same package. Likely, I will provide them a package of cabinet refinishing manassas. They can changed their cabinets with new designs and according to his desire.


Popular Posts