集册 Java实例教程 从类加载器加载一个类;如果找不到,将使用指定的上下文类的类加载器。

从类加载器加载一个类;如果找不到,将使用指定的上下文类的类加载器。

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

416
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
从类加载器加载一个类;如果找不到,将使用指定的上下文类的类加载器。
// 来自 时 代 J a v a 公 众 号

//Licensed under the Apache License, Version 2.0 (the "License");

//package com.nowjava;


public class Main {

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

        String className = "nowjava.com";

        Class context = String.class;

        boolean checkParent = true;

        System.out.println(loadClass(className, context, checkParent));

    }


    /**

     * Loads a class from the classloader; 

     * If not found, the classloader of the {@code context} class specified will be used.

     * If the flag {@code checkParent} is true, the classloader's parent is included in 

     * the lookup.

     */

    static Class<?> loadClass(String className, Class<?> context,

            boolean checkParent) {

        Class<?> clazz = null;

        try {

            clazz = Thread.currentThread().getContextClassLoader()

                    .loadClass(className);/*n o w j a v a . c o m - 时  代  Java*/

        } catch (ClassNotFoundException e) {

            if (context != null) {

                ClassLoader loader = context.getClassLoader();

                while (loader != null) {

                    try {

                        clazz = loader.loadClass(className);

                    
展开阅读全文