How to programmatically import a Java class

Is there a way in Java to programmatically import a class with a full name as a string (i.e. how "com.mydummypackage.MyClass")?

+5
source share
3 answers

If by import you mean "load an object Classso that you can run reflection methods", use:

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

(The reason our readers were confused by your word "import" is that this usually refers to the keyword importused at the top of Java class files to tell the compiler how to extend class names, for example import java.util.*;) ..

+15
source

Java - , , : http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html

, , , newInstance Class, :

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

"" .

. , , . foo.bar.Baz, Baz , , . , .

+4

All Articles