This commit was manufactured by cvs2svn to create branch 'gomp-branch'.
[official-gcc.git] / libjava / org / xml / sax / helpers / NewInstance.java
blob7d107a65239227135cc71b12c4686d242ceb8231
1 // NewInstance.java - create a new instance of a class by name.
2 // http://www.saxproject.org
3 // Written by Edwin Goei, edwingo@apache.org
4 // and by David Brownell, dbrownell@users.sourceforge.net
5 // NO WARRANTY! This class is in the Public Domain.
7 // $Id: NewInstance.java,v 1.1.2.4 2002/01/29 21:34:14 dbrownell Exp $
9 package org.xml.sax.helpers;
11 import java.lang.reflect.Method;
12 import java.lang.reflect.InvocationTargetException;
14 /**
15 * Create a new instance of a class by name.
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>
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>
29 * <p>This code is designed to compile and run on JDK version 1.1 and later
30 * including versions of Java 2.</p>
32 * @author Edwin Goei, David Brownell
33 * @version 2.0.1 (sax2r2)
35 class NewInstance {
37 /**
38 * Creates a new instance of the specified class name
40 * Package private so this code is not exposed at the API level.
42 static Object newInstance (ClassLoader classLoader, String className)
43 throws ClassNotFoundException, IllegalAccessException,
44 InstantiationException
46 Class driverClass;
47 if (classLoader == null) {
48 driverClass = Class.forName(className);
49 } else {
50 driverClass = classLoader.loadClass(className);
52 return driverClass.newInstance();
55 /**
56 * Figure out which ClassLoader to use. For JDK 1.2 and later use
57 * the context ClassLoader.
58 */
59 static ClassLoader getClassLoader ()
61 Method m = null;
63 try {
64 m = Thread.class.getMethod("getContextClassLoader", null);
65 } catch (NoSuchMethodException e) {
66 // Assume that we are running JDK 1.1, use the current ClassLoader
67 return NewInstance.class.getClassLoader();
70 try {
71 return (ClassLoader) m.invoke(Thread.currentThread(), null);
72 } catch (IllegalAccessException e) {
73 // assert(false)
74 throw new UnknownError(e.getMessage());
75 } catch (InvocationTargetException e) {
76 // assert(e.getTargetException() instanceof SecurityException)
77 throw new UnknownError(e.getMessage());