Archiviert
13
0

Merge pull request #48 from glen3b/patch-1

Minor improvements to ClassLoader
Dieser Commit ist enthalten in:
Kristian S. Stangeland 2014-05-18 12:30:52 +02:00
Commit 8067799306

Datei anzeigen

@ -1,5 +1,6 @@
package com.comphenix.protocol.utility;
import java.util.Collections;
import java.util.Map;
/**
@ -40,6 +41,7 @@ public abstract class ClassSource {
/**
* Construct a class source from a mapping of canonical names and the corresponding classes.
* If the map is null, it will be interpreted as an empty map. If the map does not contain a Class with the specified name, or that string maps to NULL explicitly, a {@link ClassNotFoundException} will be thrown.
* @param map - map of class names and classes.
* @return The class source.
*/
@ -47,11 +49,45 @@ public abstract class ClassSource {
return new ClassSource() {
@Override
public Class<?> loadClass(String canonicalName) throws ClassNotFoundException {
return map.get(canonicalName);
Class<?> loaded = map == null ? null : map.get(canonicalName);
if(loaded == null){
// Throw the appropriate exception if we can't load the class
throw new ClassNotFoundException("The specified class could not be found by this ClassLoader.");
}
return loaded;
}
};
}
/**
* @return A ClassLoader which will never successfully load a class.
*/
public static ClassSource empty(){
return fromMap(Collections.<String, Class<?>>emptyMap());
}
/**
* Retrieve a class source that will attempt lookups in each of the given sources in the order they are in the array, and return the first value that is found.
* If the sources array is null or composed of any null elements, an exception will be thrown.
* @param sources - the class sources.
* @return A new class source.
*/
public static ClassSource attemptLoadFrom(final ClassSource... sources) {
if(sources.length == 0){ // Throws NPE if sources is null, which is what we want
return ClassSource.empty();
}
ClassSource source = null;
for(int i = 0; i < sources.length; i++){
if(sources[i] == null){
throw new IllegalArgumentException("Null values are not permitted as ClassSources.");
}
source = source == null ? sources[i] : source.retry(sources[i]);
}
return source;
}
/**
* Retrieve a class source that will retry failed lookups in the given source.
* @param other - the other class source.
@ -106,7 +142,7 @@ public abstract class ClassSource {
/**
* Retrieve a class by name.
* @param canonicalName - the full canonical name of the class.
* @return The corresponding class
* @return The corresponding class. If the class is not found, NULL should <b>not</b> be returned, instead a {@code ClassNotFoundException} exception should be thrown.
* @throws ClassNotFoundException If the class could not be found.
*/
public abstract Class<?> loadClass(String canonicalName) throws ClassNotFoundException;