/*
 * Mutability Detector
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 * 
 * Further licensing information for this project can be found in
 * license/LICENSE.txt
 */

package org.mutabilitydetector.cli;

import static java.lang.String.format;

import java.net.URLClassLoader;

public class URLFallbackClassLoader {

	private final URLClassLoader urlClassLoader;

	public URLFallbackClassLoader() {
		this.urlClassLoader = getURLClassLoader();
	}

	public Class<?> getClass(String dottedClassPath) throws ClassNotFoundException {
		Class<?> toReturn = null;
		try {
			toReturn = Class.forName(dottedClassPath);
			return toReturn;
		} catch (ClassNotFoundException e) {
			toReturn = urlClassLoader.loadClass(dottedClassPath);
			return toReturn;
		}
	}
	
	private URLClassLoader getURLClassLoader() {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if(classLoader instanceof URLClassLoader) {
			return (URLClassLoader) classLoader;
		} else {
			String message = format("Expected currentThread().getContextClassLoader() to return a URLClassLoader, " +
					"but returned %s.", classLoader);
			throw new ClassCastException(message);
		}
	}
}

@@ -364,16 +364,64 @@
 sLoader;
+%0Aimport java.util.HashMap;%0Aimport java.util.Map;
 %0A%0Apublic
@@ -498,16 +498,95 @@
 sLoader;
+%0A%09private Map%3CString, Class%3C?%3E%3E classCache = new HashMap%3CString, Class%3C?%3E%3E();%0A%09
 %0A%0A%09publi
@@ -745,16 +745,114 @@
 ption %7B%0A
+%09%09if(classCache.containsKey(dottedClassPath)) %7B%0A%09%09%09return classCache.get(dottedClassPath);%0A%09%09%7D%0A%09%09%0A
 %09%09Class%3C
@@ -866,15 +866,8 @@
 turn
- = null
 ;%0A%09%09
@@ -890,21 +890,26 @@
 n = 
-Class.forName
+fromJVMClassLoader
 (dot
@@ -923,36 +923,16 @@
 sPath);%0A
-%09%09%09return toReturn;%0A
 %09%09%7D catc
@@ -976,19 +976,23 @@
 eturn = 
-url
+fromURL
 ClassLoa
@@ -998,18 +998,50 @@
 ader
-.loadClass
+(dottedClassPath);%0A%09%09%7D%0A%09%09%0A%09%09classCache.put
 (dot
@@ -1052,22 +1052,31 @@
 lassPath
+, toReturn
 );%0A%09%09
-%09
 return t
@@ -1085,22 +1085,306 @@
 eturn;%0A%09
-%09
 %7D
+%0A%0A%09private Class%3C?%3E fromJVMClassLoader(String dottedClassPath) throws ClassNotFoundException %7B%0A%09%09return Class.forName(dottedClassPath);%0A%09%7D%0A%0A%09private Class%3C?%3E fromURLClassLoader(String dottedClassPath) throws ClassNotFoundException %7B%0A%09%09return urlClassLoader.loadClass(dottedClassPath);
 %0A%09%7D%0A
+%0A
 %09%0A%09priva

Improve performance of the URLFallbackClassLoader. Non-scientific stopwatch tests showed a >10% speed increase, translating to a whopping seven seconds off when analysing rt.jar.