001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.xbean.classpath; 018 019import java.io.File; 020import java.net.URL; 021import java.net.URLClassLoader; 022 023public abstract class SunURLClassPath implements ClassPath { 024 025 public static ClassLoader getContextClassLoader() { 026 return Thread.currentThread().getContextClassLoader(); 027 } 028 029 private java.lang.reflect.Field ucpField; 030 031 protected void addJarToPath(final URL jar, final URLClassLoader loader) throws Exception { 032 this.getURLClassPath(loader).addURL(jar); 033 } 034 035 protected void addJarsToPath(final File dir, final URLClassLoader loader) throws Exception { 036 if (dir == null || !dir.exists()) return; 037 //System.out.println("DIR "+dir); 038 // Get the list of jars and zips 039 String[] jarNames = dir.list(new java.io.FilenameFilter() { 040 public boolean accept(File dir, String name) { 041 //System.out.println("FILE "+name); 042 return (name.endsWith(".jar") || name.endsWith(".zip")); 043 } 044 }); 045 046 // Create URLs from them 047 final URL[] jars = new URL[jarNames.length]; 048 for (int j = 0; j < jarNames.length; j++) { 049 jars[j] = new File(dir, jarNames[j]).toURI().toURL(); 050 } 051 052 sun.misc.URLClassPath path = getURLClassPath(loader); 053 for (int i = 0; i < jars.length; i++) { 054 //System.out.println("URL "+jars[i]); 055 path.addURL(jars[i]); 056 } 057 } 058 059 protected sun.misc.URLClassPath getURLClassPath(URLClassLoader loader) throws Exception { 060 return (sun.misc.URLClassPath) getUcpField().get(loader); 061 } 062 063 private java.lang.reflect.Field getUcpField() throws Exception { 064 if (ucpField == null) { 065 // Add them to the URLClassLoader's classpath 066 ucpField = URLClassLoader.class.getDeclaredField("ucp"); 067 ucpField.setAccessible(true); 068 } 069 return ucpField; 070 } 071 072}