Thursday, March 24, 2011

How to programmaticaly 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")?

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

  • 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();
    
  • 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.

    xelurg : aaaah... ok, I see now. Thanks a lot, this is an important bit that I've missed when reading Java 101 I guess...

0 comments:

Post a Comment