Skip to content

Commit ffb3c9b

Browse files
authored
Add path-based class loader (#39)
1 parent fba7503 commit ffb3c9b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.nordstrom.common.clazz;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.io.UncheckedIOException;
6+
import java.net.MalformedURLException;
7+
import java.net.URL;
8+
import java.net.URLClassLoader;
9+
import java.nio.file.Paths;
10+
import java.util.Arrays;
11+
12+
/**
13+
* This class implements a custom class loader initialized with a standard class path specification.
14+
*/
15+
public class CustomClassLoader extends ClassLoader {
16+
17+
private final URL[] pathUrls;
18+
19+
public CustomClassLoader(String classpath) {
20+
pathUrls = Arrays.stream(classpath.split(File.pathSeparator)).map(entry -> {
21+
try {
22+
return Paths.get(entry).toUri().toURL();
23+
} catch (MalformedURLException e) {
24+
throw new UncheckedIOException("Invalid classpath entry: " + entry, e);
25+
}
26+
}).toArray(URL[]::new);
27+
}
28+
29+
@Override
30+
protected Class<?> findClass(String name) throws ClassNotFoundException {
31+
try (URLClassLoader classLoader = new URLClassLoader(pathUrls)) {
32+
return classLoader.loadClass(name);
33+
} catch (IOException e) {
34+
throw new ClassNotFoundException("Failed loading class: " + name, e);
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)