File: ClassUtil.java

package info (click to toggle)
libgroboutils-java 5-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 7,996 kB
  • ctags: 9,436
  • sloc: java: 59,880; xml: 12,732; sh: 377; perl: 104; makefile: 20
file content (372 lines) | stat: -rw-r--r-- 12,203 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/*
 * @(#)ClassUtil.java      0.9.0 11/13/2000 - 14:06:34
 *
 * Copyright (C) 2000,2002-2003 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the 
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software. 
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 */

package net.sourceforge.groboutils.util.classes.v1;

import java.util.Hashtable;




/**
 * Utility class for loading classes and creating instances.  It decides
 * which JDK version to use as the loader.  Class instances are put
 * into a Hashtable, based on URL and classname.  When the Java-Doc defines
 * a <tt>jarName</tt>, as in {@link #getClass( String, String )}, the
 * <tt>jarName</tt> may be a filename loadable from the {@link java.io.File}
 * class, or a proper URL loadable from the {@link java.net.URL} class.
 * If the <tt>jarName</tt> does not have a protocol, then it is assumed to
 * be a file, otherwise, it is used as a URL.
 * <P>
 * Note that this class is not thread safe.  It is assumed that applications
 * will use the ClassUtil only during initialization times, since dynamic
 * class loading can be very expensive.  If you need thread safety, then you
 * will need to ensure that either all class loading is done in a single thread,
 * or that your application properly <tt>synchronize</tt>s the method calls.
 * <P>
 * Update v0.9.1: the constructor will now check for jdk2 first like before,
 * but now if it is not found, it will try to use jdk0 compatibility - before,
 * it would just fail out.  This allows the libraries to be repackaged to
 * contain only the jdk0 classes if so desired.
 *
 * @author  Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version $Date: 2003/02/10 22:52:36 $
 * @since   November 13, 2000 (GroboUtils Alpha 0.9.0)
 */
public class ClassUtil
{
    //----------------------------
    // Public data
    
    //----------------------------
    // Private data
    
    /**
     * Subclasses must instantiate themselves in this variable in their
     * static initialization block, and overload the {@link #getInstance()}
     * static method.
     */
    protected static ClassUtil s_instance = new ClassUtil();
    
    private IUrlClassLoader classLoader = null;
    private Hashtable classHash = new Hashtable();
    
    //----------------------------
    // constructors
    
    /**
     * Default constructor - made protected so
     * users won't instantiate the utility
     */
    protected ClassUtil()
    {
        // detect which JDK we're using, and from that use the correct
        // IUrlClassLoader instance.
        
        if (isJdk2Compatible())
        {
            this.classLoader = (IUrlClassLoader)createObject(
                getClassPackage( ClassUtil.class ) + ".jdk2.UrlClassLoader" );
        }
        if (this.classLoader == null)
        {
            this.classLoader = (IUrlClassLoader)createObject(
                getClassPackage( ClassUtil.class ) + ".jdk0.UrlClassLoader" );
            if (this.classLoader == null)
            {
                throw new IllegalStateException(
                    "There was an error loading a class loader." );
            }
        }
    }
    
    
    //----------------------------
    // Public Static methods
    
    
    /**
     * Retrieve the shared instance of the utility class.
     *
     * @return the utility instance
     */
    public static ClassUtil getInstance()
    {
        // Due to threading issues, the instance is created
        // in the static initialization block.
        
        return s_instance;
    }
     
     
     
    //----------------------------
    // Public methods
    
    
    /**
     * Call this to flush out the cache.  The cache may be huge, depending
     * on the Jar files loaded, as well as the Class instances.  This
     * should be called whenever a mass class instantiation process is
     * finished.
     */
    public void flush()
    {
        this.classHash = new Hashtable();
        this.classLoader.flush();
    }
    
     
    /**
     * Either finds or loads from cache the given class, using the
     * default class loader.
     *
     * @param name the name of the class to load.
     * @return the discovered Class, or <tt>null</tt> if it could not be found.
     * @see #getClass( String, String )
     */
    public Class getClass( String name )
    {
        return getClass( name, null );
    }
    
    
    /**
     * Either finds or loads from cache the given class.
     *
     * @param name the name of the class to load.
     * @param jarName the URL to load the class from - it may be <tt>null</tt>.
     * @return the discovered Class, or <tt>null</tt> if it could not be found.
     * @see #getClass( String )
     */
    public Class getClass( String name, String jarName )
    {
        String hashName = getClassHashName( name, jarName );
        Class c = (Class)classHash.get( hashName );
        if (c == null)
        {
            c = loadClass( name, jarName );
            if (c != null)
            {
                classHash.put( hashName, c );
            }
        }
        return c;
    }
    
    
    /**
     * Creates a new instance of the class with the given <tt>className</tt>
     * using the default constructor.  If there was an error during the
     * creation, such as the class was not found, the class does not have
     * a default constructor, or the constructor threw an exception, then
     * <tt>null</tt> is returned.
     *
     * @param className the name of the class to create an instance.
     * @return the new instance, or <tt>null</tt> if there was a problem.
     * @see #getClass( String )
     * @see #createObject( String, String )
     */
    public Object createObject( String className )
    {
        return createObject( className, null );
    }
    
    
    /**
     * Creates a new instance of the class with the given <tt>className</tt>
     * using the default constructor, from the given URL.  If there was an
     * error during the creation, such as the class was not found, the class
     * does not have a default constructor, or the constructor threw an
     * exception, then <tt>null</tt> is returned.
     *
     * @param className the name of the class to create an instance.
     * @param jarName the URL to load the class from - it may be <tt>null</tt>.
     * @return the new instance, or <tt>null</tt> if there was a problem.
     * @see #getClass( String, String )
     * @see #createObject( String )
     */
    public Object createObject( String className, String jarName )
    {
        return createObject( getClass( className, jarName ) );
    }
    
    
    /**
     * Creates an Object from the given Class, using its default constructor.
     * All creation exceptions are swallowed.  If the object could not
     * be created, then <tt>null</tt> is returned.
     *
     * @param c the Class object from which a new instance will be created
     *      using its default constructor.
     * @return the instantiated object, or <tt>null</tt> if <tt>c</tt> is
     *      <tt>null</tt>, or if there was an error during initialization.
     */
    public Object createObject( Class c )
    {
        if (c == null) return null;
        
        Object obj = null;
        try
        {
            obj = c.newInstance();
        }
        catch (InstantiationException ie)
        {
            System.out.println("Could not instantiate "+c.getName()+
                ": "+ie.getMessage());
            obj = null;
        }
        catch (IllegalAccessException iae)
        {
            System.out.println("Could not instantiate "+c.getName()+
                ": "+iae.getMessage());
            obj = null;
        }
        catch (NoSuchMethodError nsme)
        {
            System.out.println("Could not instantiate "+c.getName()+
                ": "+nsme.getMessage());
            obj = null;
        }
        return obj;
    }
    
    
    /**
     * Checks if the current JVM version is 1.2 compatible.  We check by
     * seeing if <tt>java.net.URLClassLoader</tt> exists.
     *
     * @return <tt>true</tt> if {@link java.net.URLClassLoader} exists
     *      in the classpath, or <tt>false</tt> otherwise.
     */
    public boolean isJdk2Compatible()
    {
        return (getClass( "java.net.URLClassLoader" ) != null);
    }
    
    
    /**
     * Discovers the package name for the given class.  The package name
     * will not have a final '.'.
     *
     * @param c the class to find the package name.
     * @return the package name, or <tt>null</tt> if <tt>c</tt> is
     *      <tt>null</tt>.
     */
    public String getClassPackage( Class c )
    {
        if (c == null)
        {
            return null;
        }
        String fullname = c.getName();
        int pos = fullname.lastIndexOf( '.' );
        if (pos < 0)
        {
            // no package
            return "";
        }
        
        // else, extract the pacakge name.
        return fullname.substring( 0, pos );
    }
     
     
    //----------------------------
    // Protected methods
    
    
    /**
     * Creates the name of the class for the hashtable lookup, which is
     * a junction of the jar name and the class name.  It allows for multiple
     * classes with the same name.
     *
     * @param name the class name
     * @param jarName the jar name - may be <tt>null</tt>.
     * @return the name for the hashtable lookup.
     */
    protected String getClassHashName( String name, String jarName )
    {
        if (jarName == null)
        {
            jarName = "<null>";
        }
        StringBuffer sb = new StringBuffer( jarName );
        sb.append( ';' );
        sb.append( name );
        return new String( sb );
    }
    
    
    /**
     * Attempts to load the class from the current classpath if <tt>baseJar</tt>
     * is <tt>null</tt>, or from the appropriate class loader if it is not
     * <tt>null</tt>.  If the class is not found, then this returns
     * <tt>null</tt>.  This never throws an exception.
     *
     * @param className name of the class to load
     * @param baseJar the URL file to load the class from - may be
     *          <tt>null</tt>.
     * @return the Class instance, or <tt>null</tt> if it was not found.
     */
    protected Class loadClass( String className, String baseJar )
    {
        Class c;
        
        try
        {
            if (baseJar == null || baseJar.length() <= 0)
            {
                try
                {
                    c = Class.forName( className );
                }
                catch (ClassNotFoundException cnfe)
                {
//                System.out.println("Class "+className+" not found");
                    c = null;
                }
            }
            else
            {
                c = this.classLoader.loadClass( className, baseJar );
            }
        }
        catch (Throwable t)
        {
            // probably a NoClassDefFoundError
            c = null;
        }
        return c;
    }
    
    
    
    //----------------------------
    // Private methods
}