1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.io.IOException;
import java.io.InputStream;

/**
 * 类加载器与instanceof演示
 * */
public class ClassLoadTest {
	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		ClassLoader classLoader = new ClassLoader() {
			@Override
			public Class<?> loadClass(String name) throws ClassNotFoundException{
				try {
					String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
					InputStream is = getClass().getResourceAsStream(fileName);
					if(is == null){
						return super.loadClass(name);
					}
					byte[] b = new byte[is.available()];
					is.read(b);
					return defineClass(name,b, 0, b.length);
				} catch (IOException e) {
					// TODO: handle exception
					throw new ClassNotFoundException(name);
				}
			}
		};
		Object object = classLoader.loadClass("com.jvm.ch7.ClassLoadTest").newInstance();
		System.out.println(object.getClass());
		System.out.println(object instanceof com.jvm.ch7.ClassLoadTest);
	}
}