[Schmitzm-commits] r1511 - trunk/schmitzm-core/src/main/java/de/schmitzm/lang

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Tue Mar 15 14:55:50 CET 2011


Author: mojays
Date: 2011-03-15 14:55:47 +0100 (Tue, 15 Mar 2011)
New Revision: 1511

Modified:
   trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java
Log:


Modified: trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java	2011-03-14 16:00:35 UTC (rev 1510)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/lang/LangUtil.java	2011-03-15 13:55:47 UTC (rev 1511)
@@ -953,6 +953,44 @@
 					.getName();
 		return className;
 	}
+	
+	/**
+	 * Instantiates an object by {@link Class#forName(String)}.
+	 * The class must be present in runtime classpath.
+	 * @param className full name of class (incl. package)
+	 * @param fallback if <code>true</code> this method returns
+	 *        <code>null</code> if {@link Class#forName(String)}
+	 *        fails
+	 * @param constrArg arguments for the constructor
+	 * @exception UnsupportedOperationException if class could be
+	 *            loaded, but no matching constructor can be found
+	 * @exception RuntimeException if class can not be loaded and
+	 *            fallback is disabled or another error occurs
+	 *            during {@link Constructor#newInstance(Object...)}
+	 */
+	public static Object instantiateObject(String className, boolean fallback, Object... constrArg) {
+      try {
+        Class<?> clazz = Class.forName(className);
+        for (Constructor constructor : clazz.getConstructors())
+          try {
+             return constructor.newInstance(constrArg);
+          } catch (IllegalArgumentException err) {
+          }
+        throw new UnsupportedOperationException(
+                "No matching constructor found...");
+      } catch (ClassNotFoundException err) {
+        // if we want to fall back, we do nothing but
+        // return NULL
+        if ( fallback )
+          return null;
+        throw new RuntimeException(err);
+      } catch (Exception err) {
+//        LOGGER.error("Unexpected error when trying to instantiate "+className,err);
+        // do not fall back, because in general the
+        // the class is supported (class present)!
+        throw new RuntimeException(err);
+      }	  
+	}
 
 	/**
 	 * Ruft die Java Garbage Collection auf.



More information about the Schmitzm-commits mailing list