[ACCEPTED]-How to get all imports defined in a class using java reflection?-dependencies
I just wanna know the list of all import 4 defined in a class using reflection
You 3 can't because the compiler doesn't put them 2 into the object file. It throws them away. Import 1 is just a shorthand to the compiler.
Imports are a compile-time feature - there's 9 no difference to the compiled code between 8 a version which uses the full name of the 7 type everywhere it's mentioned, a version 6 which imports everything using a *, and 5 a version which imports classes by full 4 name.
If you want to find all the types used within 3 the compiled code, that's a slightly different 2 matter. You may want to look at BCEL as a way 1 of analyzing bytecode.
I think you can use Qdox to get all the imports 3 in a class which is not actually through 2 reflection, but it can serve your purpose 1 :
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);
}
As suggested by @Asraful Haque qdox helps 2 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 1 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);
}
}
}
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.