1. 程式人生 > >類的相同通過對是否為同一個類載入器進行判斷

類的相同通過對是否為同一個類載入器進行判斷

類載入器相同,則類相同,否則false

package com.java.classLoader;

import java.io.IOException;
import java.io.InputStream;

public class ClassLoaderTest {
	
	public static void main(String[] args) {
		ClassLoader myLoad = new ClassLoader() {
			
			@Override
			public Class<?> loadClass(String name)throws ClassNotFoundException {
				String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
				InputStream is = getClass().getResourceAsStream(fileName);
				if (null == is) {
					return super.loadClass(name);
				}
				try {
					byte[] b= new byte[is.available()];
					is.read(b);
					return defineClass(name,b,0,b.length);
				} catch (IOException e) {
					throw new ClassNotFoundException();
				}
				
			}
		};
		
		try {
			Object obj = myLoad.loadClass("com.java.classLoader.ClassLoaderTest").newInstance();
			System.out.println(obj.getClass());
			// 這個obj使用的是自定義的classLoad 與 虛擬機器自帶的不是一個類載入器,所以返回false
			System.out.println(obj instanceof ClassLoaderTest);
			
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException e) {
			e.printStackTrace();
		}
			
	}
	
}