Thread context class loader

security.MyClassLoaderTest 入口点
Class security.MyClassLoaderTest 

package security;

import java.lang.reflect.Method;
import java.net.URL;

public class MyClassLoaderTest {

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

        URL[] urls = new URL[] {new URL("file://C:/temp4Java/external_classes/")};
        PluginClassLoader pluginClassLoader = new PluginClassLoader(urls, MyClassLoaderTest.class.getClassLoader());

        ClassLoader old = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(pluginClassLoader);
        invokePulginMethod();
        Thread.currentThread().setContextClassLoader(old);
    }

    public static void invokePulginMethod() throws Exception {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        Class clazz = loader.loadClass("gc.Foo");

        Method method = clazz.getMethod("say", (Class[]) null);

        method.setAccessible(true);
        Object obj = clazz.newInstance();
        method.invoke(obj, (Object[]) null);

        System.out.println(clazz);
        System.out.println(clazz.getClassLoader());
        System.out.println(clazz.getClassLoader().getParent());
    }
}

  

//output:

 

hei Man I am here!
class gc.Foo
security.PluginClassLoader@600060
sun.misc.Launcher$AppClassLoader@61c861c8

 

 

 Custome ClassLoader:

 

package security;

import java.net.URL;
import java.net.URLClassLoader;

public class PluginClassLoader extends URLClassLoader {

    public PluginClassLoader(final URL[] urls, final ClassLoader parent) {
        super(urls, parent);
    }

}

 

gc.Foo编译好了之后放到C:/temp4Java/external_classes/底下

 

package gc;

public class Foo {

    public void say() {

        System.out.println("hei Man I am here!");
    }
}

 

 

Bootstrap

    |

Extension

  |

System

 |

Customer

 

如果你要想在 System ClassLoader 加载的类里面使用 位于 Customer class loader指定位置的类,

办法就是只能在 System ClassLoader 加载的类里面获得一个Customer class loader,OK! 这样你就可以折腾它(Customer class loader,) 里面的类了.

 

怎么取得了:

1. 传个reference 到 System ClassLoader 加载的类.

2. 放到T hread.setContextContext 里面.

 

Done!!  Thread.getContextContext 就是这么折腾的

记录之

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值