001 // Copyright 2005 The Apache Software Foundation 002 // 003 // Licensed under the Apache License, Version 2.0 (the "License"); 004 // you may not use this file except in compliance with the License. 005 // You may obtain a copy of the License at 006 // 007 // http://www.apache.org/licenses/LICENSE-2.0 008 // 009 // Unless required by applicable law or agreed to in writing, software 010 // distributed under the License is distributed on an "AS IS" BASIS, 011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012 // See the License for the specific language governing permissions and 013 // limitations under the License. 014 015 package org.apache.hivemind.util; 016 017 import org.apache.hivemind.ApplicationRuntimeException; 018 import org.apache.hivemind.HiveMind; 019 import org.apache.hivemind.Location; 020 import org.apache.hivemind.internal.Module; 021 022 /** 023 * Code for creating an instance, possibly setting its {@link org.apache.hivemind.Location}, and 024 * possibly initializing its properties. 025 * 026 * @author Howard M. Lewis Ship 027 * @since 1.1 028 */ 029 public class InstanceCreationUtils 030 { 031 /** 032 * Creates an instance. 033 * 034 * @param module 035 * the referencing module, used to resolve partial class names 036 * @param initializer 037 * The name of the class to instantiate, possibly followed by a list of properties 038 * and values. I.e. <code>com.examples.MyBean,property=value</code>. 039 * @param location 040 * The location to assign to the newly created instance, if it implements 041 * {@link org.apache.hivemind.LocationHolder}. Also the location used to report 042 * errors creating or configuring the instance. 043 */ 044 public static Object createInstance(Module module, String initializer, Location location) 045 { 046 int commax = initializer.indexOf(','); 047 048 String className = (commax < 0) ? initializer : initializer.substring(0, commax); 049 050 Class objectClass = module.resolveType(className); 051 052 try 053 { 054 Object result = objectClass.newInstance(); 055 056 HiveMind.setLocation(result, location); 057 058 if (commax > 0) 059 PropertyUtils.configureProperties(result, initializer.substring(commax + 1)); 060 061 return result; 062 } 063 catch (Exception ex) 064 { 065 // JDK 1.4 produces a good message here, but JDK 1.3 does not, so we 066 // create our own. 067 068 throw new ApplicationRuntimeException(UtilMessages.unableToInstantiateInstanceOfClass( 069 objectClass, 070 ex), location, ex); 071 } 072 073 } 074 }