Package org.sf.mustru.utils

Source Code of org.sf.mustru.utils.ClassPathTools

package org.sf.mustru.utils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.apache.log4j.Logger;

/**
* Class to dynamically modify the classpath of the current thread
*/
public class ClassPathTools
  {
   private static Logger logger = Logger.getLogger(ClassPathTools.class.getName()); ;
   //*-- add a Jar file to the classpath
   public static void addFile(String s) throws IOException
   { addFile( new File(s)); }
   public static void addFile(File f) throws IOException
   { addURL(f.toURL()); }
   public static void addURL(URL u) throws IOException
   {
    URLClassLoader sysloader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    Class sysclass = URLClassLoader.class;
    try
     { Method method = sysclass.getDeclaredMethod("addURL", new Class[] {URL.class} );
       method.setAccessible(true);
       method.invoke(sysloader, new Object[]{ u });
     }
    catch (NoSuchMethodException ne) { logger.error("No such method " + ne.getMessage()); }
    catch (IllegalAccessException ae) { logger.error("Illegal access " + ae.getMessage()); }
    catch (InvocationTargetException te) { logger.error("Bad invocation target " + te.getMessage()); }
   }
  
   /**
    * Return a list of packages in the current application
    */
   public static String[] getPackages()
   {
    ClassLoader cloader = Thread.currentThread().getContextClassLoader();
    Class sysclass = ClassLoader.class;
    String[] packages = null;
    try
     { Method method = sysclass.getDeclaredMethod("getPackages", (Class[]) null);
       method.setAccessible(true);
       Package[] packList = (Package[]) method.invoke(cloader, (Object[]) null);
       packages = new String[packList.length];
       for (int i = 0; i < packages.length; i++) packages[i] = packList[i].toString();
     }
    catch (NoSuchMethodException ne) { logger.error("No such method " + ne.getMessage()); }
    catch (IllegalAccessException ae) { logger.error("Illegal access " + ae.getMessage()); }
    catch (InvocationTargetException te) { logger.error("Bad invocation target " + te.getMessage()); }
   
    return(packages);
   
   }
}
TOP

Related Classes of org.sf.mustru.utils.ClassPathTools

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.