範例:
public class RequestUtils {
/**
* <p>Return the <code>Class</code> object for the specified fully
* qualified class name, from this web application's class loader.</p>
*
* @param className Fully qualified class name to be loaded
* @return Class object
* @throws ClassNotFoundException if the class cannot be found
*/
public static Class applicationClass(String className)
throws ClassNotFoundException {
return applicationClass(className, null);
}
/**
* <p>Return the <code>Class</code> object for the specified fully
* qualified class name, from this web application's class loader.</p>
*
* @param className Fully qualified class name to be loaded
* @param classLoader The desired classloader to use
* @return Class object
* @throws ClassNotFoundException if the class cannot be found
*/
public static Class applicationClass(String className,
ClassLoader classLoader)
throws ClassNotFoundException {
if (classLoader == null) {
// Look up the class loader to be used
classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = RequestUtils.class.getClassLoader();
}
}
System.out.println(classLoader.loadClass(className).getName());
// Attempt to load the specified class
return (classLoader.loadClass(className));
}
public static void main(String[] args) {
try {
RequestUtils.applicationClass("cn.ehome.blog.util.PropertyMessageResources");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
輸出結果:
cn.ehome.blog.util.PropertyMessageResources