1 32 package net.sf.retrotranslator.transformer; 33 34 import java.io.*; 35 import java.net.*; 36 import java.util.*; 37 import java.util.jar.*; 38 39 42 class JarClassLoader extends URLClassLoader { 43 44 private File file; 45 46 public JarClassLoader(File file, ClassLoader parent) throws IOException { 47 super(getClassPath(file), parent); 48 this.file = file; 49 } 50 51 public String getMainClass() throws IOException { 52 return getAttribute(file, Attributes.Name.MAIN_CLASS); 53 } 54 55 private static URL[] getClassPath(File file) throws IOException { 56 Set<URL> urls = new LinkedHashSet<URL>(); 57 addToPath(urls, file); 58 return urls.toArray(new URL[urls.size()]); 59 } 60 61 private static void addToPath(Set<URL> classPath, File file) throws IOException { 62 file = file.getCanonicalFile(); 63 if (!file.exists()) return; 64 URL url = file.toURI().toURL(); 65 if (classPath.contains(url)) return; 66 classPath.add(url); 67 String attribute = getAttribute(file, Attributes.Name.CLASS_PATH); 68 if (attribute != null) { 69 StringTokenizer tokenizer = new StringTokenizer(attribute); 70 while (tokenizer.hasMoreTokens()) { 71 addToPath(classPath, new File(file.getParent(), tokenizer.nextToken())); 72 } 73 } 74 } 75 76 private static String getAttribute(File file, Attributes.Name name) { 77 Attributes attributes = getAttributes(file); 78 return attributes == null ? null : attributes.getValue(name); 79 } 80 81 private static Attributes getAttributes(File file) { 82 if (!file.isFile()) return null; 83 try { 84 JarFile jarFile = new JarFile(file); 85 try { 86 return jarFile.getManifest().getMainAttributes(); 87 } finally { 88 jarFile.close(); 89 } 90 } catch (IOException e) { 91 return null; 92 } 93 } 94 } 95 | Popular Tags |