首页   快速返回

自定义类加载器例子     所属分类 java
继承 ClassLoader
重写 loadClass 方法

    @Override
	public Class loadClass(String name,boolean resolve) throws ClassNotFoundException {
        // Cat类从指定路径加载 !!!
		if(!"dyyx.my.Cat".equals(name)){
			return super.loadClass(name,resolve);
		}
		
		byte[] bytes = readClassBytes(name);
		if (bytes == null) {
			throw new ClassNotFoundException(name);
		} else {
			// bytes to class !!!
			 Class cls = defineClass(name, bytes, 0, bytes.length);
			 if(resolve){
				 resolveClass(cls);
			 }
			 return cls;
		}
		
    }
	
	

	private byte[] readClassBytes(String name) {
		InputStream in = null;
		ByteArrayOutputStream out = null;
		String path = "/Users/dugang/tmp/Cat.class";
		try {
			in = new FileInputStream(path);
			out = new ByteArrayOutputStream();
			byte[] buffer = new byte[2048];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			return out.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
Cat.class 放到指定的路径下
Cat类从指定路径加载 !!!

public interface Pet {	
	public void sayHello();
}


Cat Dog 实现 Pet 接口



public static void main(String[] args) throws Exception {

		Class cls = Cat.class;
		
		System.out.println(cls);
		System.out.println(cls.getClassLoader());

		
		MyClassLoader myClassLoader = new MyClassLoader();
		Class cls2 = myClassLoader.loadClass("dyyx.my.Cat");
		System.out.println(cls2);
		System.out.println(cls2.getClassLoader());
		
		Class cls3 = Class.forName("dyyx.my.Dog",true,myClassLoader);
		System.out.println(cls3);
		System.out.println(cls3.getClassLoader());
		
		Class cls4 = myClassLoader.loadClass("dyyx.my.Dog");
		System.out.println(cls4);
		System.out.println(cls4.getClassLoader());
		
		System.out.println(cls.equals(cls2));
		System.out.println(cls.equals(cls3));
		System.out.println(cls.equals(cls4));

		
		Pet pet = (Pet)cls2.newInstance();
		pet.sayHello();
		
		pet = (Pet)cls3.newInstance();
		pet.sayHello();

		pet = (Pet)cls4.newInstance();
		pet.sayHello();

		
		
	}
	
	
输出结果


class dyyx.my.Cat
sun.misc.Launcher$AppClassLoader@2a139a55
class dyyx.my.Cat
dyyx.my.MyClassLoader@7852e922
class dyyx.my.Dog
sun.misc.Launcher$AppClassLoader@2a139a55
class dyyx.my.Dog
sun.misc.Launcher$AppClassLoader@2a139a55
false
false
false
cat say hello,Sun Apr 21 15:16:36 CST 2019
dog say hello,Sun Apr 21 15:16:36 CST 2019
dog say hello,Sun Apr 21 15:16:36 CST 2019

上一篇     下一篇
kafka1.1.0无法消费问题

JMX配置及java客户端远程连接JMX端口

AQS要点整理

java类加载器要点整理

kibana安装配置及使用

elasticsearch7.0压测问题记录