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