Java Class Load classForName(String className)

Here you can find the source of classForName(String className)

Description

Class.forName() cannot instantiate Class objects for primitive data types like `int'.

License

Apache License

Parameter

Parameter Description
className The name of the class or the name of a primitive data type.

Exception

Parameter Description
ClassNotFoundException If no class for the given name could be found.

Return

The Class object for the given name.

Declaration

public static Class<?> classForName(String className) throws ClassNotFoundException 

Method Source Code

//package com.java2s;
/**/*  w w w .  jav a 2  s .c o  m*/
 * Copyright 2011 The Open Source Research Group,
 *                University of Erlangen-N?rnberg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Class.forName() cannot instantiate Class objects for primitive data types
     * like `int'. This method considers these cases too.
     * 
     * @param className
     *            The name of the class or the name of a primitive data type.
     * @return The Class object for the given name.
     * @throws ClassNotFoundException
     *             If no class for the given name could be found.
     */
    public static Class<?> classForName(String className) throws ClassNotFoundException {
        if (className.equals("byte")) {
            return byte.class;
        } else if (className.equals("short")) {
            return short.class;
        } else if (className.equals("int")) {
            return int.class;
        } else if (className.equals("long")) {
            return long.class;
        } else if (className.equals("float")) {
            return float.class;
        } else if (className.equals("double")) {
            return double.class;
        } else if (className.equals("boolean")) {
            return boolean.class;
        } else if (className.equals("char")) {
            return char.class;
        } else if (className.equals("void")) {
            return void.class;
        } else {
            return Class.forName(className);
        }
    }
}

Related

  1. classForName(final String className)
  2. classForName(final String clsName)
  3. classForName(final String theClassName)
  4. classForName(String className)
  5. classForName(String className)
  6. classForName(String className)
  7. classForName(String className)