Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 887
zaree Avatar asked Apr 18 '11 10:04

zaree


People also ask

Can you find all classes in a package using reflection?

If there are classes that get generated, or delivered remotely, you will not be able to discover those classes. The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming.

Which method gets Package info using reflection?

Package Information. By using Java reflection, we are also able to get information about the package of any class or object. This data is bundled inside the Package class, which is returned by a call to getPackage method on the class object.

How do I get all classes in a classpath?

You can get all classpath roots by passing an empty String into ClassLoader#getResources() . Enumeration<URL> roots = classLoader. getResources("");

How do you reflect a class in Java?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class.


2 Answers

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.

like image 105
user207421 Avatar answered Oct 12 '22 20:10

user207421


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.

like image 16
Jon Skeet Avatar answered Oct 12 '22 20:10

Jon Skeet