01: // NewInstance.java - create a new instance of a class by name.
02: // http://www.saxproject.org
03: // Written by Edwin Goei, edwingo@apache.org
04: // and by David Brownell, dbrownell@users.sourceforge.net
05: // NO WARRANTY! This class is in the Public Domain.
06:
07: // $Id: NewInstance.java,v 1.1.1.1 2002/05/03 23:29:42 yuvalo Exp $
08:
09: package org.xml.sax.helpers;
10:
11: import java.lang.reflect.Method;
12: import java.lang.reflect.InvocationTargetException;
13:
14: /**
15: * Create a new instance of a class by name.
16: *
17: * <blockquote>
18: * <em>This module, both source code and documentation, is in the
19: * Public Domain, and comes with <strong>NO WARRANTY</strong>.</em>
20: * See <a href='http://www.saxproject.org'>http://www.saxproject.org</a>
21: * for further information.
22: * </blockquote>
23: *
24: * <p>This class contains a static method for creating an instance of a
25: * class from an explicit class name. It tries to use the thread's context
26: * ClassLoader if possible and falls back to using
27: * Class.forName(String).</p>
28: *
29: * <p>This code is designed to compile and run on JDK version 1.1 and later
30: * including versions of Java 2.</p>
31: *
32: * @author Edwin Goei, David Brownell
33: * @version 2.0.1 (sax2r2)
34: */
35: class NewInstance {
36:
37: /**
38: * Creates a new instance of the specified class name
39: *
40: * Package private so this code is not exposed at the API level.
41: */
42: static Object newInstance(ClassLoader classLoader, String className)
43: throws ClassNotFoundException, IllegalAccessException,
44: InstantiationException {
45: Class driverClass;
46: if (classLoader == null) {
47: driverClass = Class.forName(className);
48: } else {
49: driverClass = classLoader.loadClass(className);
50: }
51: return driverClass.newInstance();
52: }
53:
54: /**
55: * Figure out which ClassLoader to use. For JDK 1.2 and later use
56: * the context ClassLoader.
57: */
58: static ClassLoader getClassLoader() {
59: Method m = null;
60:
61: try {
62: m = Thread.class.getMethod("getContextClassLoader", null);
63: } catch (NoSuchMethodException e) {
64: // Assume that we are running JDK 1.1, use the current ClassLoader
65: return NewInstance.class.getClassLoader();
66: }
67:
68: try {
69: return (ClassLoader) m.invoke(Thread.currentThread(), null);
70: } catch (IllegalAccessException e) {
71: // assert(false)
72: throw new UnknownError(e.getMessage());
73: } catch (InvocationTargetException e) {
74: // assert(e.getTargetException() instanceof SecurityException)
75: throw new UnknownError(e.getMessage());
76: }
77: }
78: }
|