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

Hi, I am new to domain java reflection. Can anyone guide me in this problematic scenario.

I have a class called "SomClass.java" and it imports a package named "SomPackage.RefClass" and some other java libraries like java.lang .. etc.

Now I want to know all the imports defined in the 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 want to know the list of all imports defined in the class using reflection.

I saw that Question posted a post similar to my Q, but it is not well designed, so you need a good help line.

Thanks in advance.

+10
java reflection dependencies
source share
3 answers

I just want to know the list of all import defined in the class using reflections

You cannot, because the compiler does not put them in an object file. This throws them away. Import is just a shorthand for the compiler.

+12
source share

Import is a compile-time function - there is no difference between compiled code between a version that uses the full name of the type wherever it is mentioned, a version that imports everything using *, and a version that imports classes by full name.

If you want to find all types used in compiled code, this is a slightly different matter. You can see BCEL as a way to analyze bytecode.

+12
source share

I think you can use Qdox to get all the imports in the class, which is not actually reflected, 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); } 
+4
source share

All Articles