The Java thing.

Source: Internet
Author: User

Dynamically Loading class libraries
 PackageCP;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;Importjava.net.MalformedURLException;ImportJava.net.URL;ImportJava.net.URLClassLoader; Public classAddjar2classpath {//Although this method changes the classpath, the load jar cannot be used for the current ClassLoader    Private voidUpdateclasspath () {Classpath Classpath=NewClasspath (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); }        //This method can be used after the load jar for the current ClassLoader    Private voidLoadjar () {URL URLs; Try{URLs=NewURL ("file:/" +system.getproperty ("User.dir") + "/lib/activemq-all-5.10.0.jar"); //Getpi.classURLClassLoader UrlLoader =(URLClassLoader) Classloader.getsystemclassloader (); Class<URLClassLoader> Sysclass = URLClassLoader.class; Method Method= Sysclass.getdeclaredmethod ("Addurl",NewClass[]{url.class}); Method.setaccessible (true);                         Method.invoke (UrlLoader, URLs); URLs=NewURL ("file:/" +system.getproperty ("User.dir") + "/lib/images.jar");                         Method.invoke (UrlLoader, URLs); URLs=NewURL ("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 (); }      }}
two different methods
 PackageCP;ImportJava.io.File; Importjava.io.IOException; Importjava.net.MalformedURLException; ImportJava.net.URL; ImportJava.net.URLClassLoader; ImportJava.util.StringTokenizer; ImportJava.util.Vector; /*** Class to handle CLASSPATH construction*/   Public   classClasspath {Vector _elements=NewVector ();  PublicClasspath () {} PublicClasspath (String initial) {Addclasspath (initial); }           Public   Booleanaddcomponent (String component) {if((Component! =NULL) && (component.length () > 0))   {                          Try{File F=NewFile (component); if(F.exists ()) {File key=F.getcanonicalfile (); if(!_elements.contains (Key))                                                  {_elements.add (key); return   true; }                                  }                          }   Catch(IOException e) {}}return   false; }           Public   Booleanaddcomponent (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   BooleanAddclasspath (String s) {BooleanAdded =false; if(s! =NULL) {StringTokenizer T=NewStringTokenizer (S, file.pathseparator);  while(T.hasmoretokens ()) {Added|=addcomponent (T.nexttoken ()); }                  }                  returnadded; }           PublicString toString () {stringbuffer CP=NewStringBuffer (1024); intCNT =_elements.size (); if(CNT >= 1) {cp.append ((File) (_elements.elementat (0)) . GetPath ()); }                   for(inti = 1;   I < CNT; i++) {cp.append (File.pathseparatorchar);                  Cp.append ((File) (_elements.elementat (i))). GetPath ()); }                  returncp.tostring (); }           Publicurl[] Geturls () {intCNT =_elements.size (); Url[] URLs=Newurl[cnt];  for(inti = 0;   I < CNT; i++)   {                          Try{Urls[i]=( File) (_elements.elementat (i)). Tourl (); }   Catch(Malformedurlexception e) {}}returnURLs; }           PublicClassLoader getClassLoader () {url[] URLs=Geturls (); ClassLoader Parent=Thread.CurrentThread (). Getcontextclassloader (); if(Parent = =NULL) {Parent= Classpath.class. getClassLoader (); }                  if(Parent = =NULL) {Parent=Classloader.getsystemclassloader (); }                  return   NewURLClassLoader (URLs, parent); }  }   
class Classpath
Private voidLoadjar () {Try{urlclassloader UrlLoader=(URLClassLoader) Classloader.getsystemclassloader (); Class<URLClassLoader> Sysclass = URLClassLoader.class; Method Method= Sysclass.getdeclaredmethod ("Addurl",NewClass[]{url.class}); Method.setaccessible (true); //TODO If the jar is not added in 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=NewFile (Libdir); if(Libdirfile.isdirectory ()) {file[] libs=libdirfile.listfiles (NewFileFilter () { Public BooleanAccept (file file) {if(File.getname (). EndsWith (". Jar")) {                            return true; }                        return false;                }                });                URL URLs; if(libs!=NULL&&classpath!=NULL)                     for(inti=0;i<libs.length;i++){                        if(!Classpath.contains (Libs[i].getname ())) {System.out.println ("Libarary is not found in classpath:" +libs[i].getname ()); URLs=NewURL ("file:/" +libdir+ "/" +libs[i].getname ());                         Method.invoke (UrlLoader, URLs); }                    }                ElseSystem.out.println ("Check and load the class package:" +libdir+ "directory is null or classpath is 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 (); }      }
dynamically loading class libraries

The Java thing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.