java不同類載入器對instanceof關鍵字運算的影響

來源:互聯網
上載者:User

標籤:

內容:對於任意的一個類,都需要由載入它的類載入器和這個類本身一同確立其在Java虛擬機器中的唯一性,每一個類載入器,都擁有一個獨立的類空間。只要載入類的類載入器不同的話,那麼這個兩個類就必定不相等(包括equals()方法,instanceof()方法)。此時,虛擬機器中存在兩個ClassLoaderTest,一個是由系統應用程式類載入器載入的,另一個是由我們定義的類載入器載入的。一個簡單的例子說明:注意getResourceAsStream的應用:Class.getResourceAsStream(String path):path 不以"/"開頭時預設是從此類所在的包下取資源,以"/"開頭則是從ClassPath根下擷取,也就是bin開始。

public class ClassLoaderTest {public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {ClassLoader myLoader = new ClassLoader() {@Overridepublic Class<?> loadClass(String name) throws ClassNotFoundException {try {String className = name.substring(name.lastIndexOf(".") + 1) + ".class";//返回讀取指定資源的輸入資料流InputStream is = getClass().getResourceAsStream(className);if (is == null) return super.loadClass(name);byte[] b = new byte[is.available()];is.read(b);//將一個byte數群組轉換為Class類的執行個體return defineClass(name, b, 0, b.length);} catch (IOException e) {throw new ClassNotFoundException(name);}}};Object object = myLoader.loadClass("test.ClassLoaderTest").newInstance();System.out.println(object.getClass());System.out.println(object instanceof test.ClassLoaderTest);}}


java不同類載入器對instanceof關鍵字運算的影響

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.