码迷,mamicode.com
首页 > 编程语言 > 详细

Java那些事儿

时间:2015-01-30 16:57:33      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

动态加载类库

技术分享
package cp;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class AddJar2ClassPath {
    
    //此方法虽然改变了classpath,但是不能load Jar用于当前classloader
    private void updateClassPath(){
        Classpath   classPath   =   new Classpath(System.getProperty("java.class.path"));    
        System.out.println(System.getProperty("java.class.path"));
        classPath.addClasspath(System.getProperty("user.dir")+"/lib/activemq-all-5.10.0.jar");
        System.setProperty("java.class.path",   classPath.toString());           
        System.out.println(System.getProperty("java.class.path"));
        ClassLoader   classloader   =   classPath.getClassLoader();  
        Thread.currentThread().setContextClassLoader(classloader);   
    }
    
    //此方法load Jar后可以用于当前classloader
    private void loadJar(){
        URL urls;
        try {
            urls = new URL("file:/"+System.getProperty("user.dir")+"/lib/activemq-all-5.10.0.jar");
            //GetPI.class  
            URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();  
            Class<URLClassLoader> sysclass = URLClassLoader.class;   
            Method method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class});  
            method.setAccessible(true);  
            method.invoke(urlLoader, urls); 
            
            urls = new URL("file:/"+System.getProperty("user.dir")+"/lib/images.jar");
            method.invoke(urlLoader, urls); 
            
            urls = new URL("file:/"+System.getProperty("user.dir")+"/lib/poi-3.11-20141221.jar");
            method.invoke(urlLoader, urls); 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }  

    }

}
两种方法
技术分享
package cp;

import   java.io.File;  
import   java.io.IOException;  
import   java.net.MalformedURLException;  
import   java.net.URL;  
import   java.net.URLClassLoader;  
import   java.util.StringTokenizer;  
import   java.util.Vector;  
 
/**  
  *   Class   to   handle   CLASSPATH   construction  
  */  
public   class   Classpath   {  
        Vector   _elements   =   new   Vector();  
        public   Classpath()   {}  
        public   Classpath(String   initial)   {  
                addClasspath(initial);  
        }  
        public   boolean   addComponent(String   component)   {  
                if   ((component   !=   null)   &&   (component.length()   >   0))   {  
                        try   {  
                                File   f   =   new   File(component);  
                                if   (f.exists())   {  
                                        File   key   =   f.getCanonicalFile();  
                                        if   (!_elements.contains(key))   {  
                                                _elements.add(key);  
                                                return   true;  
                                        }  
                                }  
                        }   catch   (IOException   e)   {}  
                }  
                return   false;  
        }  
        public   boolean   addComponent(File   component)   {  
                if   (component   !=   null)   {  
                        try   {  
                                if   (component.exists())   {  
                                        File   key   =   component.getCanonicalFile();  
                                        if   (!_elements.contains(key))   {  
                                                _elements.add(key);  
                                                return   true;  
                                        }  
                                }  
                        }   catch   (IOException   e)   {}  
                }  
                return   false;  
        }  
        public   boolean   addClasspath(String   s)   {  
                boolean   added   =   false;  
                if   (s   !=   null)   {  
                        StringTokenizer   t   =   new   StringTokenizer(s,   File.pathSeparator);  
                        while   (t.hasMoreTokens())   {  
                                added   |=   addComponent(t.nextToken());  
                        }  
                }  
                return   added;  
        }  
        public   String   toString()   {  
                StringBuffer   cp   =   new   StringBuffer(1024);  
                int   cnt   =   _elements.size();  
                if   (cnt   >=   1)   {  
                        cp.append(((File)   (_elements.elementAt(0))).getPath());  
                }  
                for   (int   i   =   1;   i   <   cnt;   i++)   {  
                        cp.append(File.pathSeparatorChar);  
                        cp.append(((File)   (_elements.elementAt(i))).getPath());  
                }  
                return   cp.toString();  
        }  
        public   URL[]   getUrls()   {  
                int   cnt   =   _elements.size();  
                URL[]   urls   =   new   URL[cnt];  
                for   (int   i   =   0;   i   <   cnt;   i++)   {  
                        try   {  
                                urls[i]   =   ((File)   (_elements.elementAt(i))).toURL();  
                        }   catch   (MalformedURLException   e)   {}  
                }  
                return   urls;  
        }  
        public   ClassLoader   getClassLoader()   {  
                URL[]   urls   =   getUrls();  
                ClassLoader   parent   =   Thread.currentThread().getContextClassLoader();  
                if   (parent   ==   null)   {  
                        parent   =   Classpath.class.getClassLoader();  
                }  
                if   (parent   ==   null)   {  
                        parent   =   ClassLoader.getSystemClassLoader();  
                }  
                return   new   URLClassLoader(urls,   parent);  
        }  
}   
class Classpath
技术分享
private void loadJar(){
        try {    
            URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();  
            Class<URLClassLoader> sysclass = URLClassLoader.class;   
            Method method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class});  
            method.setAccessible(true);  
            
            //TODO 如果Jar不在classpath里面才添加
            //System.out.println(System.getProperty("java.class.path"));
            String classpath=System.getProperty("java.class.path");
            
            String libDir=System.getProperty("user.dir")+"/lib";
            File libDirFile=new File(libDir);
            if(libDirFile.isDirectory()){
                File[] libs=libDirFile.listFiles(new FileFilter() {
                    public boolean accept(File file) {
                        if (file.getName().endsWith(".jar")) {
                            return true;
                        }
                        return false;
                    }
                });
                URL urls;
                if(libs!=null&&classpath!=null)
                    for(int i=0;i<libs.length;i++){
                        if(!classpath.contains(libs[i].getName())){
                            System.out.println("Libarary is not found in classpath:"+libs[i].getName());
                            urls = new URL("file:/"+libDir+"/"+libs[i].getName());
                            method.invoke(urlLoader, urls); 
                        }
                    }
                else
                    System.out.println("检查并加载类包:"+libDir+"目录为null或者classpath为null!");
            }
            
//            URL urls = new URL("file:/"+System.getProperty("user.dir")+"/lib/activemq-all-5.10.0.jar");
//            method.invoke(urlLoader, urls); 
//            
//            urls = new URL("file:/"+System.getProperty("user.dir")+"/lib/images.jar");
//            method.invoke(urlLoader, urls); 
//            
//            urls = new URL("file:/"+System.getProperty("user.dir")+"/lib/poi-3.11-20141221.jar");
//            method.invoke(urlLoader, urls); 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }  
    }
动态加载类库

 

Java那些事儿

标签:

原文地址:http://www.cnblogs.com/markjiao/p/4262365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!