4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javax.tools.ToolProviderを使用して、指定パッケージ以下のClassを取得

Posted at

ちょっと長いです。

	@SuppressWarnings("rawtypes")
	private static Set<Class> getClasses(String packageName) {
    	JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    	JavaFileManager jfm = compiler.getStandardFileManager(
    	    new DiagnosticCollector<JavaFileObject>(), null, null);

    	// 一覧に含めるオブジェクト種別。以下はクラスのみを含める場合。
    	Set<JavaFileObject.Kind> kind = new HashSet<JavaFileObject.Kind>();
    	kind.add(JavaFileObject.Kind.CLASS);
    	
    	// ブートクラスパスから、指定のパッケージ以下のクラス一覧を取得する。
    	boolean recursive = true;
    	Set<Class> classes = new HashSet<Class>();
    	
		try {
			for ( JavaFileObject jfo : jfm.list(StandardLocation.CLASS_PATH, packageName, kind, recursive)) {
				String uri = null;

				try {
				    uri = jfo.toUri().toString();
				    // [/]はFile.separatorにしないとだめかも。
				    String uriDotSeparate = uri.replaceAll("/", ".");
				    
				    int indexOfPkgNmBegin = uriDotSeparate.indexOf(packageName);
				    String fqcnWithExtension = uriDotSeparate.substring(indexOfPkgNmBegin);
				    String fqcn = fqcnWithExtension.substring(0, fqcnWithExtension.length() - ".class".length());
				    
				    Class clazz = Class.forName(fqcn);
				    classes.add(clazz);
				} catch (NoClassDefFoundError e) {
					System.out.println("get class failed. " + uri);
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					System.out.println("get class failed. " + uri);
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			System.out.println("list class failed. packageName=" + packageName);
			e.printStackTrace();
		}
		return classes;
	}
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?