Java ClassPath Add addBundleToClassPath(String bundleId)

Here you can find the source of addBundleToClassPath(String bundleId)

Description

add Bundle To Class Path

License

Open Source License

Declaration

private static void addBundleToClassPath(String bundleId) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010, 2013 EclipseSource and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from  w ww  . j  av a  2 s.c  om*/
 *    EclipseSource - initial API and implementation
 ******************************************************************************/

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    private static final String BUNDLE_ID = "org.eclipse.rap.rwt.themes.test";

    private static void addBundleToClassPath(String bundleId) {
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        if (systemClassLoader instanceof URLClassLoader) {
            URLClassLoader classLoader = (URLClassLoader) systemClassLoader;
            String path = getBundlePath(classLoader, bundleId);
            addFolderToClassPath(classLoader, path);
        }
    }

    private static String getBundlePath(URLClassLoader classLoader, String bundleId) {
        URL[] urls = classLoader.getURLs();
        String path = null;
        for (int i = 0; i < urls.length && path == null; i++) {
            String tempPath = urls[i].getPath();
            if (tempPath.contains(bundleId) && tempPath.indexOf(BUNDLE_ID) == -1) {
                int indexOfBin = tempPath.indexOf("bin");
                if (indexOfBin != -1) {
                    String protocol = urls[i].getProtocol();
                    path = protocol + ":" + tempPath.substring(0, indexOfBin);
                }
            }
        }
        return path;
    }

    private static void addFolderToClassPath(URLClassLoader classLoader, String path) {
        if (path != null) {
            Class<?> clazz = URLClassLoader.class;
            try {
                Class[] params = new Class[] { URL.class };
                Method method = clazz.getDeclaredMethod("addURL", params);
                method.setAccessible(true);
                Object[] url = new Object[] { new URL(path) };
                method.invoke(classLoader, url);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. addAllFilesToExtClassLoaderClasspathWithReg(String sDir, String regexpFilter)
  2. addClassPath(File filePath)
  3. addClasspath(String path)
  4. addClassPath2ClassLoader(ClassLoader cl, String path)
  5. addClasspathEntries(Collection cpEntries)