Listing Classes in a Java Package
July 18, 2014
I needed to list the Classes that existed in a Java Package. It isn't possible to do this with the default JVM, but there is a third party library called Reflections that can do the job.
Once the library and its dependencies are on the classpath, the following code can be used to go through the classes in a package and create instances of them. In this case, the constructor has no parameters and all the classes inherit from MyAbstractClass
. This code is for Java 7.
Reflections lReflections = new Reflections("com.drumcoder.package"); Set<Class<? extends MyAbstractClass>> lClasses = lReflections.getSubTypesOf(MyAbstractClass.class); Iterator<Class<? extends MyAbstractClass>> lIterator = lClasses.iterator(); while (lIterator.hasNext()) { Class<? extends MyAbstractClass> lEachClass = lIterator.next(); String lClassName = lEachClass.getSimpleName(); MyAbstractClass lClassInstance; try { Constructor<?> lClassConstructor = lEachClass.getConstructor(); lClassInstance = (MyAbstractClass) lClassConstructor.newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException lException) { throw new RuntimeException("Can't create instance of class " + lClassName, lException); } System.out.println(" - " + lClassInstance.getTableName()); }