Java Class forName forName(Class classType, String className)

Here you can find the source of forName(Class classType, String className)

Description

Creates a new instance of an object given it's class name.

License

Open Source License

Parameter

Parameter Description
classType the class that the instantiated object should be assignable to -- an exception is thrown if this is not the case
className the fully qualified class name of the object May be null. Any options accepted by the object will be removed from the array.

Return

the newly created object, ready for use.

Declaration

public static Object forName(Class classType, String className) throws Exception 

Method Source Code

//package com.java2s;
/*/*w  w  w.j  av a 2  s . co m*/
Open Auto Trading : A fully automatic equities trading platform with machine learning capabilities
Copyright (C) 2015 AnyObject Ltd.
    
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Creates a new instance of an object given it's class name.
     *
     * @param classType the class that the instantiated object should be
     * assignable to -- an exception is thrown if this is not the case
     * @param className the fully qualified class name of the object May be
     * null. Any options accepted by the object will be removed from the array.
     * @return the newly created object, ready for use.
     * @exception Exception if the class name is invalid, or if the class is not
     * assignable to the desired class type, or the options supplied are not
     * acceptable to the object
     */
    public static Object forName(Class classType, String className) throws Exception {

        Class c = null;
        try {
            c = Class.forName(className);
        } catch (Exception ex) {
            throw new Exception("Can't find class called: " + className);
        }

        if (!classType.isAssignableFrom(c)) {
            throw new Exception(classType.getName() + " is not assignable from " + className);
        }

        return c.newInstance();
    }
}

Related

  1. forName(final Class caller, final String className)
  2. forName(final String className)
  3. forName(final String className, final Class caller)
  4. forName(String className)