java 如何使用java反射获取类中定义的所有导入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5701305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:22:43  来源:igfitidea点击:

How to get all imports defined in a class using java reflection?

javareflectiondependencies

提问by zaree

Hi i am new in java reflection domain.So can anyone guide me in this problem scenario.

嗨,我是 Java 反射域的新手。所以任何人都可以在这个问题场景中指导我。

I have a classnamed "SomClass.java"and it imports a packagenamed "SomPackage.RefClass"And some other java libraries like java.lang.. etc.

我有一个名为“SomClass.java”,它导入一个名为“SomPackage.RefClass”的包和一些其他的 java 库,如 java.lang.. 等。

Now i wish to get know all the imports defined in a class through reflection.

现在我希望通过反射了解一个类中定义的所有导入。

import SomPackage.RefClass;
import java.lang.reflect.Field;
import java.io.IOException; 
 public class SomeClass{
  RefClass refClass_Obj;
  String nationality;
///some other members
}

I just wanna know the list of all import defined in a class using reflection.

我只想知道使用反射在类中定义的所有导入的列表。

I have seen a Questionposted hear similar to my Q but it is not well elaborated so,need some good direction of help.

我看到发布的问题与我的 Q 相似,但没有很好地阐述,因此需要一些好的帮助方向。

thanks in advance.

提前致谢。

回答by user207421

I just wanna know the list of all import defined in a class using reflection

我只想知道使用反射在类中定义的所有导入的列表

You can't because the compiler doesn't put them into the object file. It throws them away. Import is just a shorthand to the compiler.

你不能,因为编译器没有把它们放到目标文件中。它把它们扔掉。导入只是编译器的简写。

回答by Jon Skeet

Imports are a compile-time feature - there's no difference to the compiled code between a version which uses the full name of the type everywhere it's mentioned, a version which imports everything using a *, and a version which imports classes by full name.

导入是一个编译时功能 - 使用类型的全名的版本,使用 * 导入所有内容的版本和按全名导入类的版本之间的编译代码没有区别。

If you want to find all the types usedwithin the compiled code, that's a slightly different matter. You may want to look at BCELas a way of analyzing bytecode.

如果您想找到编译代码中使用的所有类型,那是一个稍微不同的问题。您可能希望将BCEL视为分析字节码的一种方式。

回答by Asraful Haque

I think you can use Qdoxto get all the imports in a class which is not actually through reflection, but it can serve your purpose :

我认为您可以使用Qdox来获取类中的所有导入,这实际上不是通过反射,但它可以满足您的目的:

    String fileFullPath = "Your\java\ file \full\path";
    JavaDocBuilder builder = new JavaDocBuilder();
    builder.addSource(new FileReader( fileFullPath  ));

    JavaSource src = builder.getSources()[0];
    String[] imports = src.getImports();

    for ( String imp : imports )
    {
        System.out.println(imp);
    }