xelurg
xelurg

Reputation: 4304

How to programmatically import Java class

Is there a way in Java to programmatically import a class given its full name as a String (i.e. like "com.mydummypackage.MyClass")?

Upvotes: 5

Views: 3050

Answers (3)

duffymo
duffymo

Reputation: 308743

Don't confuse "import" with class loading.

The import statement doesn't load anything. All it does is save you from having to type out the fully resolved class name. If you import foo.bar.Baz, you can refer to class Baz in your code instead of having to spell it out. That's all import means.

Upvotes: 4

CalvinR
CalvinR

Reputation: 744

The Java Documentation is a great source of knowledge for stuff like this, I suggest you read up on the Class Object Documentation which can be found here: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html

As mentioned in Jason Cohen's answer you can load a Class object using the following line of code and then to create an instance of that class you would execute the newInstance method of the Class object like so:

Class<?> clazz = Class.forName( "com.mypackage.MyClass" );
Object o = clazz.newInstance();

Upvotes: 6

Jason Cohen
Jason Cohen

Reputation: 83011

If by "import" you mean "load a Class object so you can run reflection methods," then use:

Class<?> clazz = Class.forName( "com.mypackage.MyClass" );

(The reason we readers were confused by your word "import" is that typically this refers to the import keyword used near the top of Java class files to tell the compiler how to expand class names, e.g. import java.util.*;).

Upvotes: 15

Related Questions