11

package com.ailk;

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.List;
import com.ailk.dynamic.Demo;
public class DemoMain {
    static public void main( String args[] ) throws Exception {
        String progClass ="com.ailk.dynamic.Demo";
        // 创建CompilingClassLoader
        Class c = Class.forName(progClass, true, new CompilingClassLoader());
        //DemoInterface i=(DemoInterface)c.newInstance();

        //cl1和cl2是两个不同的ClassLoader
        ClassLoader cl1=c.getClassLoader();
        ClassLoader cl2=Demo.class.getClassLoader();
        ClassLoader cl3=DemoInterface.class.getClassLoader();

        int ii=0;
        List<DemoInterface> objList=new ArrayList();
        while(true){
            ii++;
            CompilingClassLoader ccl = new CompilingClassLoader();
            // 通过CCL加载主函数类。
            Class clas = ccl.loadClass( progClass,true);
            try{
                Constructor c1=c.getDeclaredConstructor(new Class[]{String.class}); 
                c1.setAccessible(true);   
                DemoInterface a1=(DemoInterface)c1.newInstance(new Object[]{"Demo"});
            }catch(NoSuchMethodException e){
                System.out.println("构造函数不存在");
                e.printStackTrace();
            }

            DemoInterface instance=null;
            try{
                Constructor c0=clas.getDeclaredConstructor();
                c0.setAccessible(true);   
                instance=(DemoInterface)c0.newInstance();  
            }catch(NoSuchMethodException e){
                System.out.println("构造函数不存在");
                e.printStackTrace();
            }

            ccl=null;//这里讲主动释放cc1
            //DemoInterface instance=(DemoInterface)clas.newInstance();
            if (instance!=null)
            {
                objList.add(instance);
                instance.print("demo");
                // 利用反射调用它的函数和传递参数。
                // 产生一个代表主函数的参数类型的类对象。
                Class mainArgType[] = { String.class };
                //在类中找函数。
                Method method = clas.getMethod( "print", mainArgType );
                Object[] argsArray={"Demo"};
                //调用方法。
                method.invoke(instance, argsArray );                

            }
            if (ii>20)
            {
                ii=0;
                objList.clear();
            }
            Thread.sleep(500);
            //强制gc,只有objList清空后 CompilingClassLoader的实例才会释放。
            //因为只有由CompilingClassLoader载入的class的实例全部释放后,CompilingClassLoader才能被释放
            System.gc();

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值