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

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.


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 used within the compiled code, that's a slightly different matter. You may want to look at BCEL as a way of analyzing bytecode.


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

    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);
    }