KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > hivemind > service > impl > JavassistBeanInterfaceFactory


1 // Copyright 2006 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.service.impl;
16
17 import javassist.ClassPool;
18 import javassist.CtClass;
19 import javassist.CtMethod;
20 import javassist.LoaderClassPath;
21
22 import org.apache.hivemind.ApplicationRuntimeException;
23 import org.apache.hivemind.Location;
24 import org.apache.hivemind.definition.ImplementationConstructionContext;
25 import org.apache.hivemind.internal.AbstractServiceImplementationConstructor;
26 import org.apache.hivemind.service.ClassFabUtils;
27
28 /**
29  * @author James Carman
30  */

31 public class JavassistBeanInterfaceFactory extends AbstractServiceImplementationConstructor
32 {
33
34     public JavassistBeanInterfaceFactory(Location location, String JavaDoc contributingModuleId)
35     {
36         super(location);
37     }
38
39     public Object JavaDoc constructCoreServiceImplementation(ImplementationConstructionContext context)
40     {
41         return createJavassistBean();
42     }
43
44     /**
45      * @return
46      */

47     public static BeanInterface createJavassistBean() {
48         try {
49             ClassPool classPool = new ClassPool();
50             classPool.appendClassPath(new LoaderClassPath(BeanInterface.class
51                     .getClassLoader()));
52             CtClass theClass = classPool
53                     .makeClass(ClassFabUtils.generateClassName( BeanInterface.class ) );
54
55             theClass.addInterface(classPool.get(BeanInterface.class.getName()));
56             CtMethod theMethod = new CtMethod(
57                     classPool.get("java.lang.String"), "interfaceMethod",
58                     new CtClass[0], theClass);
59             theMethod.setBody("return \"Hello, World!\";");
60             theClass.addMethod(theMethod);
61             Class JavaDoc clazz = theClass.toClass();
62             return ( BeanInterface )clazz.newInstance();
63         } catch (Exception JavaDoc e) {
64             throw new ApplicationRuntimeException("Cannot construct instance.",
65                     e);
66         }
67     }
68
69 }
70
Popular Tags