16

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

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

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 Question posted hear similar to my Q but it is not well elaborated so,need some good direction of help.

thanks in advance.

Community
  • 1
  • 1
zaree
  • 641
  • 2
  • 6
  • 15
  • See here (http://stackoverflow.com/questions/17928121/get-list-of-necessary-classes-for-a-class-to-load) for an answer which doesn't use reflection, or source code parsing, but bytecode reading instead. – carlspring Jul 30 '13 at 09:55

5 Answers5

18

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    As u explain "You can't because the compiler doesn't put them into the object file." I have try this and when i decompile a java file using some java Decompiler like DJ Java Decompiler.it will show all the imports(java libraries & as well packages).Can u explain this more? – zaree Apr 18 '11 at 11:19
  • 2
    @zaree No it won't. It will synthesize import statements for all the classes from other packages used by this class. It is not recreating the original source code. – user207421 May 20 '11 at 00:27
16

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @zaree - for completeness, there is no way to determine the types used within a type using the reflection APIs. – Stephen C Apr 18 '11 at 11:26
8

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);
    }
ThisClark
  • 14,352
  • 10
  • 69
  • 100
Asraful Haque
  • 753
  • 8
  • 11
  • 2
    No you can't. From your own link: 'QDox is a high speed, small footprint parser for extracting class/interface/method definitions from *source* files ...' [emphasis added] – user207421 Jan 07 '15 at 17:12
  • 5
    Yes you are right, through reflection its not possible. But with Qdox its possible to get from .java file which might be useful for some others. – Asraful Haque Jan 28 '15 at 06:32
1

As suggested by @Asraful Haque qdox helps to read imports of java file

Use Maven dependency

        <dependency>
            <groupId>com.thoughtworks.qdox</groupId>
            <artifactId>qdox</artifactId>
            <version>2.0.1</version>
        </dependency>

Please refer modified version of code

package readimports;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Collection;
import java.util.List;

import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaSource;

public class TestReadAllImport {

    public static void main(String[] args) throws FileNotFoundException {
        String fileFullPath = "path to java file";
        JavaProjectBuilder builder = new JavaProjectBuilder();
        builder.addSource(new FileReader( fileFullPath  ));

        Collection<JavaSource> srcs = builder.getSources();
        for(JavaSource src : srcs) {
            List<String> imports = src.getImports();

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

}
Darshan Shah
  • 365
  • 4
  • 12
0

Thanks for sharing the qdox, I used it to recursively find all imports and find unique packages and unique imports.

<!-- https://mvnrepository.com/artifact/com.thoughtworks.qdox/qdox -->
<dependency>
    <groupId>com.thoughtworks.qdox</groupId>
    <artifactId>qdox</artifactId>
    <version>2.0.3</version>
</dependency>

Using simple recursion to get all packages and imports of the given class.

package test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaSource;

public class ImportsIdentifier {

    private static String sysPath ="//<Absolute Path>/src/main/java/";
    private static String fileType = ".java";
    private static Set<String> importFiles = new HashSet<>();
    private static Set<String> packages = new HashSet<>();
    
    public static void main(String[] args) throws FileNotFoundException {
        String path = sysPath + "<java file path>";
        
        printImports(path);
        
        System.out.println(importFiles);
        System.out.println(packages);
    }
    
    private static void printImports(String path) throws FileNotFoundException {
        JavaProjectBuilder jp = new JavaProjectBuilder();
        jp.addSource(new FileReader(path));

        Collection<JavaSource> srcs = jp.getSources();

        for (JavaSource src : srcs) {
            System.out.println(src.getPackage());
            packages.add(src.getPackage().toString());
            
            for(String imprt: src.getImports()) {
                if(imprt.startsWith("<filter for any package>")) {
                    
                    imprt = sysPath+imprt.replaceAll("\\.", "/")+fileType;
                    if(importFiles.contains(imprt)) {
                        continue;
                    }
                    importFiles.add(imprt);
                    System.out.println(imprt);
                    
                    printImports(imprt);
                }
            }
        }
    }

}
Sushant Verma
  • 899
  • 7
  • 8