通过ClassLoader调用外部jar包

               

我们大家都知道,每个运行中的线程都有一个成员contextClassLoader,用来在运行时动态地载入其它类。

系统默认的contextClassLoader是systemClassLoader,所以一般而言java程序在执行时可以使用JVM自带的类、$JAVA_HOME/jre/lib/ext/中的类和$CLASSPATH/中的类,对于非默认的jar,一般只能手动在配置环境添加。

但事实上,我们可以通过Thread.currentThread().setContextClassLoader()更改当前线程的contextClassLoader行为,实现在程序内加载外部jar。

PS:
ClassLoader的工作原理是:
1) 线程需要用到某个类时,contextClassLoader将被请求来载入该类
2) contextClassLoader请求它的父ClassLoader来完成该载入请求
3) 如果父ClassLoader无法载入类,则contextClassLoader试图自己来载入



package  org.loon.framework.jar;

/** */ /**
 * <p>Title: LoonFramework</p>
 * <p>Description:JarLoader,用于jar包的外部操作</p>
 * <p>Copyright: Copyright (c) 2007</p>
 * <p>Company: LoonFramework</p>
 * @author chenpeng  
 * @email:ceponline@yahoo.com.cn 
 * @version 0.1
 */

import  java.io.BufferedInputStream;
import  java.io.ByteArrayInputStream;
import  java.io.ByteArrayOutputStream;
import  java.io.File;
import  java.io.FileInputStream;
import  java.io.FileNotFoundException;
import  java.io.IOException;
import  java.io.InputStream;
import  java.lang.reflect.Method;
import  java.net.MalformedURLException;
import  java.net.URL;
import  java.util.ArrayList;
import  java.util.HashMap;
import  java.util.Hashtable;
import  java.util.jar.JarEntry;
import  java.util.jar.JarInputStream;
import  java.util.jar.Manifest;

public   class  JarLoader  extends  ClassLoader  ... {
    //资源缓存
    public static Hashtable resources = new Hashtable();
 
    public static JarLoader loader = new JarLoader();

    public static Class load(byte[] resource) throws Exception ...{
        // 主函数所在类全称
        String mainClassName = "";
        //class资源及实体缓存
        ArrayList classNames = new ArrayList();
        ArrayList classBuffers = new ArrayList();
        // 存储依赖类
        HashMap depends = new HashMap();
        // 将byte[]转为JarInputStream
        JarInputStream jar = new JarInputStream(new ByteArrayInputStream(
                resource));
        Manifest manifest = jar.getManifest();
        // 当Main-Class被声明时,获得主函数所在类全称
        if (manifest != null) ...{
            mainClassName = manifest.getMainAttributes().getValue("Main-Class");
        }

        // 依次获得对应JAR文件中封装的各个被压缩文件的JarEntry
        JarEntry entry;
        while ((entry = jar.getNextJarEntry()) != null) ...{
            // 当找到的entry为class时
            if (entry.getName().toLowerCase().endsWith(".class")) ...{
                // 将类路径转变为类全称
                String name = entry.getName().substring(0,
                        entry.getName().length() - ".class".length()).replace(
                        '/', '.');
                // 加载该类
                byte[] data = getResourceData(jar);
                // 缓存类名及数据
                classNames.add(name);
                classBuffers.add(data);

            }
 else ...{
                // 非class结尾但开头字符为'/'时
                if (entry.getName().charAt(0) == '/') ...{
                    resources.put(entry.getName(), getResourceData(jar));
                // 否则追加'/'后缓存    
                }
 else ...{
                    resources.put("/" + entry.getName(), getResourceData(jar));
                }

            }

        }

        //当获得的main-class名不为空时
        while (classNames.size() > 0) ...{
            //获得类路径全长
            int n = classNames.size();
            for (int i = classNames.size() - 1; i >= 0; i--) ...{
                try ...{
                    //查询指定类
                    loader.defineClass((String) classNames.get(i),
                            (byte[]) classBuffers.get(i), 0,
                            ((byte[]) classBuffers.get(i)).length);
                    //获得类名
                    String pkName = (String) classNames.get(i);
                    if (pkName.lastIndexOf('.') >= 0) ...{
                        pkName = pkName
                                .substring(0, pkName.lastIndexOf('.'));
                        if (loader.getPackage(pkName) == null) ...{
                            loader.definePackage(pkName, null, null, null,
                                    null, null, null, null);
                        }

                    }

                    //查询后删除缓冲
                    classNames.remove(i);
                    classBuffers.remove(i);
                }
 catch (NoClassDefFoundError e) ...{
                    depends.put((String) classNames.get(i), e.getMessage()
                            .replaceAll("/", "."));
                }
 catch (UnsupportedClassVersionError e) ...{
                    //jre版本错误提示
                    throw new UnsupportedClassVersionError(classNames.get(i)
                            + ", " + System.getProperty("java.vm.name") + " "
                            + System.getProperty("java.vm.version") + ")");
                }

            }

            if (n == classNames.size()) ...{
                for (int i = 0; i < classNames.size(); i++) ...{
                    System.err.println("NoClassDefFoundError:"
                            + classNames.get(i));
                    String className = (String) classNames.get(i);
                    while (depends.containsKey(className)) ...{
                        className = (String) depends.get(className);
                    }

                }

                break;
            }

        }

        try ...{
            //加载
            Thread.currentThread().setContextClassLoader(loader);
            // 获得指定类,查找其他类方式相仿
            return Class.forName(mainClassName, true, loader);
        }
 catch (ClassNotFoundException e) ...{
            String className = mainClassName;
            while (depends.containsKey(className)) ...{
                className = (String) depends.get(className);
            }

            throw new ClassNotFoundException(className);
        }

    }


    /** *//**
     * 获得指定路径文件的byte[]形式
     * @param name
     * @return
     */

    final static public byte[] getDataSource(String name) ...{
        FileInputStream fileInput;
        try ...{
            fileInput = new FileInputStream(new File(name));
        }
 catch (FileNotFoundException e) ...{
            fileInput = null;
        }

        BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
        return getDataSource(bufferedInput);
    }

    
    /** *//**
     * 获得指定InputStream的byte[]形式
     * @param name
     * @return
     */

    final static public byte[] getDataSource(InputStream is) ...{
        if (is == null) ...{
            return null;
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] arrayByte = null;
        try ...{
            byte[] bytes = new byte[8192];
            bytes = new byte[is.available()];
            int read;
            while ((read = is.read(bytes)) >= 0) ...{
                byteArrayOutputStream.write(bytes, 0, read);
            }

            arrayByte = byteArrayOutputStream.toByteArray();
        }
 catch (IOException e) ...{
            return null;
        }
 finally ...{
            try ...{
                if (byteArrayOutputStream != null) ...{
                    byteArrayOutputStream.close();
                    byteArrayOutputStream = null;
                }

                if (is != null) ...{
                    is.close();
                    is = null;
                }


            }
 catch (IOException e) ...{
            }

在Java中,当你需要从一个jar包中读取外部配置文件时,你可以采取以下步骤: 1. 确定配置文件的位置:首先,你需要确定配置文件的存放位置。配置文件通常放在项目的资源目录下(例如`src/main/resources`),打包成jar后,这些资源文件会位于jar包的`META-INF`目录下。 2. 获取资源流:在你的Java代码中,你可以使用类加载器(ClassLoader)来获取资源文件的输入流。可以使用`Thread.currentThread().getContextClassLoader()`或者`getClass().getClassLoader()`来获取当前线程的上下文类加载器或当前类的类加载器。 3. 读取文件内容:有了输入流之后,你可以使用IO流(如`BufferedReader`)来读取配置文件的内容。 下面是一个示例代码,展示如何在Java中读取位于`META-INF`目录下的配置文件`config.properties`: ```java import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.Properties; public class ConfigReader { public static Properties readConfig() { Properties config = new Properties(); try { // 使用当前类的类加载器获取资源输入流 InputStream inputStream = ConfigReader.class.getClassLoader().getResourceAsStream("META-INF/config.properties"); if (inputStream == null) { throw new RuntimeException("No config.properties found in the classpath."); } config.load(new InputStreamReader(inputStream, "UTF-8")); } catch (Exception e) { e.printStackTrace(); } return config; } public static void main(String[] args) { Properties config = readConfig(); // 输出读取到的配置信息,例如: System.out.println(config.getProperty("key")); } } ``` 请注意,配置文件读取可能会出现文件不存在、文件读取错误等情况,因此应当妥善处理这些异常情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值