动态加载jar包的方法

时间:2022-05-01 20:10:54

String strDir = System.getProperty("user.dir"); //获取项目所在目录的绝对路径

strDir = strDir.replace('//',File.separatorChar);   //将目录分隔符号换掉

if (taskName == null || taskName.length() <= 0 || initClass == null) {
           
        }
        try {
            //不同的包内Class.forName的路径不同
            URL[] us = {new URL("file:" + strDir + File.pathSeparator+ jarPath)};  //jarPath为jar包名和后缀
            ClassLoader loader = new URLClassLoader(us);
            Class c = loader.loadClass(initClass);
//            Class c = Class.forName(initClass);
            TaskBase task = (TaskBase) c.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }