KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > hivemind > util > InstanceCreationUtils


1 // Copyright 2005 The Apache Software Foundation
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
// http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15 package org.apache.hivemind.util;
16
17 import org.apache.hivemind.ApplicationRuntimeException;
18 import org.apache.hivemind.HiveMind;
19 import org.apache.hivemind.Location;
20 import org.apache.hivemind.internal.Module;
21
22 /**
23  * Code for creating an instance, possibly setting its {@link org.apache.hivemind.Location}, and
24  * possibly initializing its properties.
25  *
26  * @author Howard M. Lewis Ship
27  * @since 1.1
28  */

29 public class InstanceCreationUtils
30 {
31     /**
32      * Creates an instance.
33      *
34      * @param module
35      * the referencing module, used to resolve partial class names
36      * @param initializer
37      * The name of the class to instantiate, possibly followed by a list of properties
38      * and values. I.e. <code>com.examples.MyBean,property=value</code>.
39      * @param location
40      * The location to assign to the newly created instance, if it implements
41      * {@link org.apache.hivemind.LocationHolder}. Also the location used to report
42      * errors creating or configuring the instance.
43      */

44     public static Object JavaDoc createInstance(Module module, String JavaDoc initializer, Location location)
45     {
46         int commax = initializer.indexOf(',');
47
48         String JavaDoc className = (commax < 0) ? initializer : initializer.substring(0, commax);
49
50         Class JavaDoc objectClass = module.resolveType(className);
51
52         try
53         {
54             Object JavaDoc result = objectClass.newInstance();
55
56             HiveMind.setLocation(result, location);
57
58             if (commax > 0)
59                 PropertyUtils.configureProperties(result, initializer.substring(commax + 1));
60
61             return result;
62         }
63         catch (Exception JavaDoc ex)
64         {
65             // JDK 1.4 produces a good message here, but JDK 1.3 does not, so we
66
// create our own.
67

68             throw new ApplicationRuntimeException(UtilMessages.unableToInstantiateInstanceOfClass(
69                     objectClass,
70                     ex), location, ex);
71         }
72
73     }
74 }
Popular Tags