1 19 20 package edu.umd.cs.findbugs.classfile; 21 22 import java.lang.reflect.Constructor ; 23 import java.lang.reflect.InvocationTargetException ; 24 import java.lang.reflect.Method ; 25 import java.lang.reflect.Modifier ; 26 27 28 39 public class ReflectionDatabaseFactory<E> implements IDatabaseFactory<E> { 40 private Class <E> databaseClass; 41 42 public ReflectionDatabaseFactory(Class <E> databaseClass) { 43 this.databaseClass = databaseClass; 44 } 45 46 49 public E createDatabase() throws CheckedAnalysisException { 50 E database; 51 52 database = createUsingStaticCreateMethod(); 53 if (database != null) { 54 return database; 55 } 56 57 database = createUsingConstructor(); 58 if (database != null) { 59 return database; 60 } 61 62 throw new CheckedAnalysisException( 63 "Could not find a way to create database " + databaseClass.getName()); 64 } 65 66 72 private E createUsingStaticCreateMethod() throws CheckedAnalysisException { 73 Method createMethod; 74 try { 75 createMethod = databaseClass.getMethod("create", new Class [0]); 76 } catch (NoSuchMethodException e) { 77 return null; 78 } 79 80 if (!Modifier.isStatic(createMethod.getModifiers())) { 81 return null; 82 } 83 84 if (createMethod.getReturnType() != databaseClass) { 85 return null; 86 } 87 88 try { 89 return (E) createMethod.invoke(null, new Object [0]); 90 } catch (InvocationTargetException e) { 91 throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e); 92 } catch (IllegalAccessException e) { 93 throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e); 94 } 95 } 96 97 103 private E createUsingConstructor() throws CheckedAnalysisException { 104 Constructor <E> constructor; 105 try { 106 constructor = databaseClass.getConstructor(new Class [0]); 107 } catch (NoSuchMethodException e) { 108 return null; 109 } 110 111 try { 112 return constructor.newInstance(new Object [0]); 113 } catch (InstantiationException e) { 114 throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e); 115 } catch (IllegalAccessException e) { 116 throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e); 117 } catch (InvocationTargetException e) { 118 throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e); 119 } 120 } 121 122 125 public void registerWith(IAnalysisCache analysisCache) { 126 analysisCache.registerDatabaseFactory(databaseClass, this); 127 } 128 129 } 130 | Popular Tags |