How to create a class instance by using class name in Java?

The Class.forName() method allows you to map a case-sensitive class name to the Class instance representing gaven class. Then you can invoke its newInstance() to create an instance of that class.  For Example:

   Class tc = Class.forName("com.xyzws.common.Type");
   Tyep myType = tc.newInstance();

In the event that the Class could not be found, resolved, verified, or loaded, Class.forName
throws one of several different Exceptions, all of which are listed in the javadoc page for

Another example to check where class's jar file is:

    try {
        String qualifiedClassName="org.xbill.DNS.DSRecord";
        Class qc = Class.forName(qualifiedClassName);
        CodeSource source = qc.getProtectionDomain().getCodeSource();
        if ( source != null ) {
            URL location = source.getLocation();
            System.out.println( qualifiedClassName + " : " + location );
        else {
            System.out.println( qualifiedClassName + " : "
                 + "unknown source, likely rt.jar" );
     catch ( Exception e ) {
        System.err.println( "Unable to locate class on command line." );


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |