集册 Java实例教程 将所有罐子添加到类路径

将所有罐子添加到类路径

欢马劈雪     最近更新时间:2020-01-02 10:19:05

436
将所有罐子添加到类路径

/*******************************************************************************

 * CopyRight (c) 2005-2011 GLOBE Co, Ltd. All rights reserved.

 * Filename:    JVMUtil.java

 * Creator:     joe

 * Create-Date: 2011-4-27 ????10:39:08

 *******************************************************************************/

//package com.nowjava;
/* from 
N o  w  J a v a . c o m - 时  代  Java*/

import java.io.File;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;


public class Main {

    public static String[] addAllJarsToClassPath(String dirName) {

        List<String> ret = new ArrayList<String>();


        File dir = new File(dirName);

        if (dir.isDirectory()) {

            File[] files = dir.listFiles();

            for (File file : files) {

                if (file.isDirectory()) {

                    ret.addAll(Arrays.asList(addAllJarsToClassPath(file

                            .getAbsolutePath())));

                } else {/*n o w j a v a . c o m 提供*/

                    String filename = file.getName().toLowerCase();

                    if (filename.endsWith(".jar")) {

                        if (appendtoClassPath(file.getAbsolutePath())) {

                            ret.add(file.getAbsolutePath());

                        }

                    }

                }

            }

        }


        return ret.toArray(new String[0]);

    }


    public static boolean appendtoClassPath(String name) {

        // ??? JDK 1.6

        // from JDK DOC "java.lang.instrument Interface Instrumentation"

        // ...

        // The system class loader supports adding a JAR file to be searched

        // if it implements a method named appendToClassPathForInstrumentation

        // which takes a single parameter of type java.lang.String.

        // The method is not required to have public access. The name of the JAR

        // file

        // is obtained by invoking the getName() method on the jarfile and this

        // is

        // provided as the parameter to the appendtoClassPathForInstrumentation

        // method.

        // ...


        try {

            ClassLoader clsLoader = ClassLoader.getSystemClassLoader();

            Method appendToClassPathMethod = clsLoader.getClass()

                    .getDeclaredMethod(

                            "appendToClassPathForInstrumentation",

                            String.class);

            if (null != appendToClassPathMethod) {

                appendToClassPathMethod.setAccessible(true);

                appendToClassPathMethod.invoke(clsLoad
展开阅读全文