001 // Copyright 2004, 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.service.impl; 016 017 import javassist.CtClass; 018 import javassist.NotFoundException; 019 020 import org.apache.hivemind.ApplicationRuntimeException; 021 import org.apache.hivemind.service.ClassFabUtils; 022 023 /** 024 * Wrapper around Javassist's {@link javassist.ClassPool} and our own 025 * {@link org.apache.hivemind.service.impl.ClassFactoryClassLoader} that manages the creation of new 026 * instance of {@link javassist.CtClass} and converts finished CtClass's into instantiable Classes. 027 * 028 * @author Howard Lewis Ship 029 */ 030 public class CtClassSource 031 { 032 private HiveMindClassPool _pool; 033 034 private int _createdClassCount = 0; 035 036 /** 037 * Returns the number of classes (and interfaces) created by this source. 038 * 039 * @see #createClass(CtClass) 040 * @return the count 041 * @since 1.2 042 */ 043 public int getCreatedClassCount() 044 { 045 return _createdClassCount; 046 } 047 048 public CtClassSource(HiveMindClassPool pool) 049 { 050 _pool = pool; 051 } 052 053 public CtClass getCtClass(Class searchClass) 054 { 055 ClassLoader loader = searchClass.getClassLoader(); 056 057 // Add the class loader for the searchClass to the class pool and 058 // delegating class loader if needed. 059 060 _pool.appendClassLoader(loader); 061 062 String name = ClassFabUtils.getJavaClassName(searchClass); 063 064 try 065 { 066 return _pool.get(name); 067 } 068 catch (NotFoundException ex) 069 { 070 throw new ApplicationRuntimeException(ServiceMessages.unableToLookupClass(name, ex), ex); 071 } 072 } 073 074 public CtClass newClass(String name, Class superClass) 075 { 076 CtClass ctSuperClass = getCtClass(superClass); 077 078 return _pool.makeClass(name, ctSuperClass); 079 } 080 081 /** 082 * Creates a new, empty interace, with the given name. 083 * 084 * @since 1.1 085 */ 086 087 public CtClass newInterface(String name) 088 { 089 return _pool.makeInterface(name); 090 } 091 092 public Class createClass(CtClass ctClass) 093 { 094 // String className = ctClass.getName(); 095 096 try 097 { 098 Class result = _pool.toClass(ctClass); 099 100 _createdClassCount++; 101 102 return result; 103 } 104 catch (Throwable ex) 105 { 106 throw new ApplicationRuntimeException(ServiceMessages.unableToWriteClass(ctClass, ex), 107 ex); 108 } 109 } 110 }