一、前言
关于dyuproject-util-1.1.6.jar源码包中的com.dyuproject.util.ClassLoaderUtil类加载器工具类,对指定类名称class对象加载loadClass、对指定class对象加载实例化newInstance及获取指定class路径下的getResource资源URL等操作。
二、源码说明
package com.dyuproject.util;@b@@b@import java.net.URL;@b@@b@public final class ClassLoaderUtil@b@{@b@ public static Class<?> loadClass(String className, Class<?> context)@b@ {@b@ return loadClass(className, context, false);@b@ }@b@@b@ public static Class<?> loadClass(String className, Class<?> context, boolean checkParent)@b@ {@b@ Class clazz = null;@b@ try@b@ {@b@ clazz = Thread.currentThread().getContextClassLoader().loadClass(className);@b@ }@b@ catch (ClassNotFoundException e)@b@ {@b@ if (context != null)@b@ {@b@ ClassLoader loader = context.getClassLoader();@b@ if (loader != null)@b@ {@b@ try@b@ {@b@ clazz = loader.loadClass(className);@b@ return clazz;@b@ }@b@ catch (ClassNotFoundException e1)@b@ {@b@ loader = (checkParent) ? loader.getParent() : null;@b@ }@b@ }@b@ }@b@ }@b@ return clazz;@b@ }@b@@b@ public static <T> T newInstance(String className, Class<?> context)@b@ throws Exception@b@ {@b@ Class clazz = loadClass(className, context, false);@b@ if (clazz == null)@b@ throw new Exception(className + " not found in the classpath.");@b@@b@ return clazz.newInstance();@b@ }@b@@b@ public static <T> T newInstance(String className, Class<?> context, boolean checkParent)@b@ throws Exception@b@ {@b@ Class clazz = loadClass(className, context, checkParent);@b@ if (clazz == null)@b@ throw new Exception(className + " not found in the classpath.");@b@@b@ return clazz.newInstance();@b@ }@b@@b@ public static URL getResource(String resource, Class<?> context)@b@ {@b@ return getResource(resource, context, false);@b@ }@b@@b@ public static URL getResource(String resource, Class<?> context, boolean checkParent)@b@ {@b@ URL url = Thread.currentThread().getContextClassLoader().getResource(resource);@b@ if (url != null)@b@ return url;@b@@b@ if (context != null)@b@ {@b@ ClassLoader loader = context.getClassLoader();@b@ while (loader != null)@b@ {@b@ url = loader.getResource(resource);@b@ if (url != null)@b@ return url;@b@ loader = (checkParent) ? loader.getParent() : null;@b@ }@b@ }@b@@b@ return ClassLoader.getSystemResource(resource);@b@ }@b@}