「Java パッケージ配下のクラスを取得する」の版間の差分
ナビゲーションに移動
検索に移動
7行目: | 7行目: | ||
public void getClassesInPackage(Package package) throws Exception { | public void getClassesInPackage(Package package) throws Exception { | ||
final char PACKAGE_SEP = '.'; | final char PACKAGE_SEP = '.'; | ||
− | final char | + | final char PACKAGE_RESOURCE_SEP = '/'; |
String packageName = package.getName(); | String packageName = package.getName(); | ||
− | String | + | String packageResource |
− | = packageName.replace(PACKAGE_SEP, | + | = packageName.replace(PACKAGE_SEP, PACKAGE_RESOURCE_SEP); |
− | logger.info(" | + | logger.info("RESOURCE:" + packageResource); |
ClassLoader loader = ClassLoader.getSystemClassLoader(); | ClassLoader loader = ClassLoader.getSystemClassLoader(); | ||
− | + | URL resource = loader.getResource(packageResource); | |
File f = new File(resource.getPath()); | File f = new File(resource.getPath()); |
2022年5月19日 (木) 14:36時点における最新版
Java パッケージ配下のクラスを取得する
Java |
/** * @param package getClass().getPackage(); */ public void getClassesInPackage(Package package) throws Exception { final char PACKAGE_SEP = '.'; final char PACKAGE_RESOURCE_SEP = '/'; String packageName = package.getName(); String packageResource = packageName.replace(PACKAGE_SEP, PACKAGE_RESOURCE_SEP); logger.info("RESOURCE:" + packageResource); ClassLoader loader = ClassLoader.getSystemClassLoader(); URL resource = loader.getResource(packageResource); File f = new File(resource.getPath()); for (String file : f.list()) { if (file.matches(".*\\.class$")) { String className = packageName + PACKAGE_SEP + file.replaceAll("\\.class$",""); logger.info("CLASS:" + className); @SuppressWarnings("rawtypes") Class cls = Class.forName(className); logger.info("OBJECT:" + cls.newInstance()); } } }
© 2006 矢木浩人