// 上下文類加載器 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // 當前類 classLoader = Main.class.getClassLoader(); // 系統 classLoader = ClassLoader.getSystemClassLoader();
老是使用上下文類加載器」或者「老是使用當前類加載器spring
通常來講,上下文類加載器要比當前類加載器更適合於框架編程,而當前類加載器則更適合於業務邏輯編程。 編程
// spring 加載器 public static ClassLoader getDefaultClassLoader() { ClassLoader cl = null; try { cl = Thread.currentThread().getContextClassLoader(); } catch (Throwable ex) { // Cannot access thread context ClassLoader - falling back... } if (cl == null) { // No thread context class loader -> use class loader of this class. cl = ClassUtils.class.getClassLoader(); if (cl == null) { // getClassLoader() returning null indicates the bootstrap ClassLoader try { cl = ClassLoader.getSystemClassLoader(); } catch (Throwable ex) { // Cannot access system ClassLoader - oh well, maybe the caller can live with null... } } } return cl; }
ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class c = classLoader.loadClass("Main"); Main main = (Main) c.newInstance(); main.show();
讀取 src/main/resources/app.conf 配置文件bootstrap
try { Properties properties = new Properties(); InputStream inputStream = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("app.conf"); properties.load(inputStream); } catch (Exception e) { e.printStackTrace(); }
參考:app
http://blog.csdn.net/xyang81/article/details/7292380框架
http://blog.chinaunix.net/uid-21227800-id-65885.htmlui
http://blog.csdn.net/zhoutaohenan/article/details/8467271this