1842
|
1 package goodjava.io;
|
|
2
|
|
3 import java.io.File;
|
|
4 import java.io.FileInputStream;
|
|
5 import java.io.BufferedInputStream;
|
|
6 import java.io.IOException;
|
|
7 import java.net.URL;
|
|
8 import java.net.URLClassLoader;
|
|
9 import java.net.MalformedURLException;
|
|
10 import java.util.List;
|
|
11 import java.util.ArrayList;
|
|
12 import java.util.Map;
|
|
13 import java.util.HashMap;
|
|
14
|
|
15
|
|
16 public class FileClassLoader extends URLClassLoader {
|
|
17
|
|
18 public static final class FileInfo {
|
|
19 public final File file;
|
|
20 private final long checksum;
|
|
21
|
|
22 public FileInfo(File file) throws IOException {
|
|
23 this.file = file;
|
|
24 this.checksum = IoUtils.checksum( new BufferedInputStream( new FileInputStream(file) ) );
|
|
25 }
|
|
26
|
|
27 public boolean equals(Object obj) {
|
|
28 if( !(obj instanceof FileInfo) )
|
|
29 return false;
|
|
30 FileInfo fi = (FileInfo)obj;
|
|
31 return this.checksum==fi.checksum && this.file.getName().equals(fi.file.getName());
|
|
32 }
|
|
33
|
|
34 public int hashCode() {
|
|
35 return (int)checksum;
|
|
36 }
|
|
37 }
|
|
38
|
|
39 private static URL[] toURLs(List<FileInfo> files) {
|
|
40 int n = files.size();
|
|
41 URL[] urls = new URL[n];
|
|
42 for( int i=0; i<n; i++ ) {
|
|
43 try {
|
|
44 urls[i] = files.get(i).file.toURI().toURL();
|
|
45 } catch(MalformedURLException e) {
|
|
46 throw new RuntimeException(e);
|
|
47 }
|
|
48 }
|
|
49 return urls;
|
|
50 }
|
|
51
|
|
52 private final List<FileInfo> files;
|
|
53
|
|
54 private FileClassLoader(List<FileInfo> files) {
|
|
55 super(toURLs(files));
|
|
56 this.files = new ArrayList<FileInfo>(files);
|
|
57 }
|
|
58
|
|
59 public List<FileInfo> getFiles() {
|
|
60 return new ArrayList<FileInfo>(files);
|
|
61 }
|
|
62
|
|
63 private static final Map<List<FileInfo>,FileClassLoader> map = new HashMap<List<FileInfo>,FileClassLoader>();
|
|
64
|
|
65 public static synchronized FileClassLoader getFileClassLoader(List<FileInfo> files) {
|
|
66 FileClassLoader fcl = map.get(files);
|
|
67 if( fcl == null ) {
|
|
68 fcl = new FileClassLoader(files);
|
|
69 map.put(fcl.files,fcl);
|
|
70 }
|
|
71 return fcl;
|
|
72 }
|
|
73 }
|