6

I'd like to obtain the list of imports a class has. Since this is removed by the compiler, I suppose via reflection one could scan through the class, it's methods, fields and so on and collect a list of classes which are required in order for the classloader to load the class. Is there some sort of library, tutorial, or article you could point me at so I could better understand how this can be done? (I understand similar questions have been asked, but I could not find a proper answer and I'm quite sure this should be possible). I saw some examples showing how you could do it, if you had the sources, but that would not necessarily be the case in my scenario.

Many thanks in advance!

4

2 回答 2

9

不,反思无济于事

void test() {
    Date date = new Date();
}

您无法检测到 Date 在反射方法中使用。但是你可以使用 Javassist https://github.com/jboss-javassist/javassist

    ClassPool cp = ClassPool.getDefault();
    Collection classes = cp.get("test.Test").getRefClasses();

此代码生成 test.Test 类中引用的所有类的名称的集合

于 2013-07-29T15:36:35.063 回答
1

我认为这是不可能的,除非通过读取源 .java 文件本身。我相当确定Java只是在编译期间使用列表进行扫描然后将其丢弃。

然而,Spring 会做这样的事情,并且有一个谷歌项目可以扫描包中的注释等(忘记名称——类路径?)。

我建议您研究一下 Spring,它很可能完全符合您的要求,并且做得更多,并且以一种下一个程序员会自动理解的方式(如果他们知道 Spring)来做。

于 2013-07-29T15:38:48.107 回答