集册 Java实例教程 从类名称获取类。

从类名称获取类。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

420
从类名称获取类。


//package com.nowjava;// 来自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m


import java.security.AccessController;

import java.security.PrivilegedAction;


public class Main {

    /**

     * Get the Class from the class name.

     * <p>

     * The context class loader will be utilized if accessible and non-null.

     * Otherwise the defining class loader of this class will

     * be utilized.

     *

     * @param name the class name.

     * @return the Class, otherwise null if the class cannot be found.

     */

    public static Class classForName(String name) {

        return classForName(name, getContextClassLoader());

    }


    /**

     * Get the Class from the class name.

     *

     * @param name the class name.

     * @param cl the class loader to use, if null then the defining class loader

     * of this class will be utilized.

     * @return the Class, otherwise null if the class cannot be found.

     */

    public static Class classForName(String name, ClassLoader cl) {

        if (cl != null) {

            try {

                return Class.forName(name, false, cl);

            } catch (ClassNotFoundException ex) {//from nowjava.com - 时代Java

            }

        }

        try {

            return Class.forName(name);

        } catch (ClassNotFoundException ex) {

        }


        return null;

    }


    /**

     * Get the context class loader.

     *

     * @return the context class loader, otherwise null security privilages

     *         are not set.

     */

    public static ClassLoader getContextClassLoader() {

        return AccessController

                .doPrivileged(new PrivilegedAction<ClassLoader>() {

                    public ClassLoader run() {

              
展开阅读全文