Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")?

like image 898
xelurg Avatar asked Jan 22 '09 21:01

xelurg


People also ask

How to get the class of an object?

If you have a JavaSW object, you can obtain it's class object by calling getClass() on the object. To determine a String representation of the name of the class, you can call getName() on the class.

How to call class object in Java?

To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main. java).

How to get class type of a class in Java?

Java provides three different ways to find the type of an object at runtime like instanceof keyword, getClass(), and isInstance() method of java. lang. Class.


1 Answers

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.*;).

like image 83
Jason Cohen Avatar answered Oct 01 '22 01:10

Jason Cohen