コード例 #1
0
ファイル: MaryRuntimeUtils.java プロジェクト: sal1023/marytts
 /**
  * Instantiate an object by calling one of its constructors.
  *
  * @param objectInitInfo a string description of the object to instantiate. The objectInitInfo is
  *     expected to have one of the following forms:
  *     <ol>
  *       <li>my.cool.Stuff
  *       <li>my.cool.Stuff(any,string,args,without,spaces)
  *       <li>my.cool.Stuff(arguments,$my.special.property,other,args)
  *     </ol>
  *     where 'my.special.property' is a property in one of the MARY config files.
  * @return the newly instantiated object.
  * @throws ClassNotFoundException
  * @throws IllegalArgumentException
  * @throws InstantiationException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  * @throws SecurityException
  * @throws NoSuchMethodException
  */
 public static Object instantiateObject(String objectInitInfo) throws MaryConfigurationException {
   Object obj = null;
   String[] args = null;
   String className = null;
   try {
     if (objectInitInfo.contains("(")) { // arguments
       int firstOpenBracket = objectInitInfo.indexOf('(');
       className = objectInitInfo.substring(0, firstOpenBracket);
       int lastCloseBracket = objectInitInfo.lastIndexOf(')');
       args = objectInitInfo.substring(firstOpenBracket + 1, lastCloseBracket).split(",");
       for (int i = 0; i < args.length; i++) {
         if (args[i].startsWith("$")) {
           // replace value with content of property named after the $
           args[i] = MaryProperties.getProperty(args[i].substring(1));
         }
         args[i] = args[i].trim();
       }
     } else { // no arguments
       className = objectInitInfo;
     }
     Class<? extends Object> theClass = Class.forName(className).asSubclass(Object.class);
     // Now invoke Constructor with args.length String arguments
     if (args != null) {
       Class<String>[] constructorArgTypes = new Class[args.length];
       Object[] constructorArgs = new Object[args.length];
       for (int i = 0; i < args.length; i++) {
         constructorArgTypes[i] = String.class;
         constructorArgs[i] = args[i];
       }
       Constructor<? extends Object> constructor =
           (Constructor<? extends Object>) theClass.getConstructor(constructorArgTypes);
       obj = constructor.newInstance(constructorArgs);
     } else {
       obj = theClass.newInstance();
     }
   } catch (Exception e) {
     // try to make e's message more informative if possible
     throw new MaryConfigurationException(
         "Cannot instantiate object from '"
             + objectInitInfo
             + "': "
             + MaryUtils.getFirstMeaningfulMessage(e),
         e);
   }
   return obj;
 }