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 */ 017 018package org.apache.commons.lang3; 019 020import java.net.URL; 021import java.net.URLClassLoader; 022import java.util.Arrays; 023 024/** 025 * Helps work with {@link ClassLoader}. 026 * 027 * @since 3.10 028 */ 029public class ClassLoaderUtils { 030 031 private static final URL[] EMPTY_URL_ARRAY = new URL[] {}; 032 033 /** 034 * Gets the system class loader's URLs, if any. 035 * 036 * @return the system class loader's URLs, if any. 037 * @since 3.13.0 038 */ 039 public static URL[] getSystemURLs() { 040 return getURLs(ClassLoader.getSystemClassLoader()); 041 } 042 043 /** 044 * Gets the current thread's context class loader's URLs, if any. 045 * 046 * @return the current thread's context class loader's URLs, if any. 047 * @since 3.13.0 048 */ 049 public static URL[] getThreadURLs() { 050 return getURLs(Thread.currentThread().getContextClassLoader()); 051 } 052 053 private static URL[] getURLs(final ClassLoader cl) { 054 return cl instanceof URLClassLoader ? ((URLClassLoader) cl).getURLs() : EMPTY_URL_ARRAY; 055 } 056 057 /** 058 * Converts the given class loader to a String calling {@link #toString(URLClassLoader)}. 059 * 060 * @param classLoader to URLClassLoader to convert. 061 * @return the formatted string. 062 */ 063 public static String toString(final ClassLoader classLoader) { 064 if (classLoader instanceof URLClassLoader) { 065 return toString((URLClassLoader) classLoader); 066 } 067 return classLoader.toString(); 068 } 069 070 /** 071 * Converts the given URLClassLoader to a String in the format {@code "URLClassLoader.toString() + [URL1, URL2, ...]"}. 072 * 073 * @param classLoader to URLClassLoader to convert. 074 * @return the formatted string. 075 */ 076 public static String toString(final URLClassLoader classLoader) { 077 return classLoader + Arrays.toString(classLoader.getURLs()); 078 } 079}