1 package com.bonevich.util;
2 import org.apache.commons.logging.Log;
3 import org.apache.commons.logging.LogFactory;
4
5 import java.io.File;
6 import java.io.IOException;
7 import java.net.URL;
8 import java.net.URLClassLoader;
9 import java.util.*;
10 import java.util.jar.JarEntry;
11 import java.util.jar.JarFile;
12 /***
13 * ClassDescription
14 *
15 * @author jbonevic
16 * @version $Id: JarFileClassLoader.html,v 1.1 2009/03/07 17:55:37 jbonevic Exp $
17 */
18 public class JarFileClassLoader extends URLClassLoader
19 {
20 private static final Log _logger = LogFactory.getLog(JarFileClassLoader.class);
21
22 private String _jarFilePath;
23 private JarFile _jarFile;
24 private Map _classMap = new HashMap(10);
25
26 /***
27 * Constructor for JarFileClassLoader.
28 * @param arg0
29 * @param arg1
30 * @param arg2
31 */
32 public JarFileClassLoader(String path, Object obj)
33 throws IOException
34 {
35 super(new URL[] {}, obj.getClass().getClassLoader());
36 _jarFilePath = path;
37 _jarFile = new JarFile(path);
38 File file = new File(path);
39 try
40 {
41 addURL(file.toURL());
42 }
43 catch (Exception e)
44 {
45 throw new IOException(e.getMessage());
46 }
47 }
48
49 public Vector loadClasses(Class parentClass)
50 {
51 Vector classes = (Vector) _classMap.get(parentClass.getName());
52 if (classes == null)
53 {
54 classes = new Vector();
55 try
56 {
57 Enumeration entries = _jarFile.entries();
58 while (entries.hasMoreElements())
59 {
60 JarEntry entry = (JarEntry) entries.nextElement();
61 String entryName = entry.getName();
62 int index = entryName.indexOf(".class");
63 if (index > 0)
64 {
65 try
66 {
67 entryName = entryName.replace('/','.').substring(0,index);
68 if (_logger.isDebugEnabled())
69 {
70 _logger.debug("entry = " + entryName);
71 }
72 Class jarredClass = loadClass(entryName);
73 if (_logger.isDebugEnabled())
74 {
75 _logger.debug("loaded class = " + jarredClass.getName());
76 _logger.debug("interfaces = " + Arrays.asList(jarredClass.getInterfaces()));
77 }
78 if (parentClass.isAssignableFrom(jarredClass))
79 {
80 classes.add(jarredClass);
81 }
82 }
83 catch (Exception e)
84 {
85 _logger.error("Could not load class for " + entryName, e);
86 }
87 }
88 }
89 }
90 catch (Exception e)
91 {
92 _logger.error("No jar file specified or error reading one", e);
93 }
94 _classMap.put(parentClass.getName(), classes);
95 }
96 return classes;
97 }
98
99 public Vector loadClasses(Class parentClass, Functor f)
100 {
101 Vector classes = loadClasses(parentClass);
102 Vector transformedClasses = new Vector();
103 Iterator itr = classes.iterator();
104 while (itr.hasNext())
105 {
106 transformedClasses.add(f.function(itr.next()));
107 }
108 return transformedClasses;
109 }
110 }
This page was automatically generated by Maven