Here you can find the source of getClassesInPackage(String targetPackage)
Parameter | Description |
---|---|
targetPackage | target package |
public static Class[] getClassesInPackage(String targetPackage)
//package com.java2s; /*/*from w w w . j av a 2 s . c o m*/ * ReflectionHelper * * 8/23/13 * * Copyright (c) 2013, Marcus Stojcevich * All rights reserved. * See the included LICENSE file */ import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; public class Main { /** * Returns an array of classes within a target package * @param targetPackage target package * @return an array of classes within a target package */ public static Class[] getClassesInPackage(String targetPackage) { List<Class> classList = new ArrayList<Class>(); URL packageResource = Thread.currentThread().getContextClassLoader() .getResource(targetPackage.replace(".", "/").trim()); if (packageResource == null) { System.out.println("Could not create resource for package " + targetPackage); return null; } File packageDirectory = new File(packageResource.getFile()); for (String filename : packageDirectory.list()) { if (filename.endsWith(".class")) { String className = targetPackage + "." + filename; try { classList.add(Class.forName(className.replace(".class", ""))); } catch (ClassNotFoundException e) { System.out.println("Error attempting to load classes from " + targetPackage); e.printStackTrace(); } } } return classList.toArray(new Class[classList.size()]); } }