append to Class Path - Java Reflection

Java examples for Reflection:Class Path

Description

append to Class Path

Demo Code

/*******************************************************************************
 * CopyRight (c) 2005-2011 GLOBE Co, Ltd. All rights reserved.
 * Filename:    JVMUtil.java/*w  w w . ja va  2s. com*/
 * Creator:     joe
 * Create-Date: 2011-4-27 ????10:39:08
 *******************************************************************************/
//package com.java2s;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    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(clsLoader, name);
            }
            return true;
        } 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();
        }
        return false;
    }
}

Related Tutorials