public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, MalformedURLException { // String path = // "/xx/.m2/repository/org/apache/commons/commons-lang3/3.1/commons-lang3-3.1.jar"; String path = "commons-lang3-3.1.jar";//jar文件需放在工程目录下 loadJar(path); Class<?> aClass = Class.forName("org.apache.commons.lang3.StringUtils"); Object instance =aClass.newInstance (); Object Strip = aClass.getDeclaredMethod ( "Strip", String. class , String. class ) .invoke (instance, "[1,2,3,4,5,6,2,3,5, . 1] "," [] " ); System.out.println (Strip); } Private static void loadJar (String jarpath) throws a MalformedURLException { file jarFile = new new file (jarpath); // get a class where the class files from URLClassLoader methods clip, jar can also be considered a folder IF (jarFile.exists () == false ) { System.out.println ( "JAR file not found."); Return ; } // Get method of the class loader addURL prepared dynamic invocation Method, Method = null ; the try { Method = the URLClassLoader. Class .getDeclaredMethod ( "addURL", the URL. Class ); } the catch (a NoSuchMethodException | a SecurityException E1) { e1.printStackTrace (); } // get access methods, saving the original values Boolean accessible = method.isAccessible (); the try { // modify access to writable IF (== accessibleto false ) { method.setAccessible ( to true ); } // Get the system class loader the URLClassLoader classLoader = (the URLClassLoader) ClassLoader.getSystemClassLoader (); // Get path jar file url the java.net.URL url = jarFile.toURI () .toURL (); // JAR url path added to the system in the path Method.invoke (classLoader, url); } the catch (Exception E) { e.printStackTrace (); } the finally { // writeback access method.setAccessible ( Accessible); } }
Reference article: