集册 Java实例教程 从给定的类加载器开始加载一个类(可以为null,然后使用默认的类加载器)

从给定的类加载器开始加载一个类(可以为null,然后使用默认的类加载器)

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

418
从给定的类加载器开始加载一个类(可以为null,然后使用默认的类加载器)


//package com.nowjava;


public class Main {/** 来自 nowjava.com - 时代Java**/

    public static void main(String[] argv) throws Exception {

        String name = "nowjava.com";

        System.out.println(forName(name));

    }


    /**

     * Loads a class starting from the given class loader (can be null, then use

     * default class loader)

     * 

     * @param loader

     * @param name

     *            of class to load

     * @return

     * @throws ClassNotFoundException

     */

    public static Class forName(final ClassLoader loader, final String name)

            throws ClassNotFoundException {

        Class klass = null;

        if (loader != null) {

            klass = Class.forName(name, false, loader);/*来自 n o w    j a v a  . c o m*/

        } else {

            klass = Class.forName(name, false,

                    ClassLoader.getSystemClassLoader());

        }

        return klass;

    }


    /**

     * Loads a class from the context class loader or, if that fails, from the

     * default class loader.

     * 

     * @param name

     *            is the name of the class to load.

     * @return a <code>Class</code> object.

     * @throws ClassNotFoundException

     *             if the class was not found.

     */

    public static Class forName(final String name)

            throws ClassNotFoundException {

        
展开阅读全文