1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
|
public final class EntityHelperFactory {
private static final Map<Class<?>, AbstractEntityHelper> _entityHelperMap = new HashMap<>();
private EntityHelperFactory() { }
public static AbstractEntityHelper getEntityHelper(Class<?> entityClazz) throws Exception { if (null == entityClazz) { return null; }
AbstractEntityHelper helperObj = _entityHelperMap.get(entityClazz);
if (helperObj != null) { return helperObj; }
ClassPool pool = ClassPool.getDefault(); pool.appendSystemPath();
pool.importPackage(ResultSet.class.getName()); pool.importPackage(entityClazz.getName());
CtClass abstractEntityHelperClazz = pool.getCtClass(AbstractEntityHelper.class.getName()); final String helperImplClazzName = entityClazz.getName() + "_Helper";
CtClass helperClazz = pool.makeClass(helperImplClazzName, abstractEntityHelperClazz);
CtConstructor constructor = new CtConstructor(new CtClass[0], helperClazz); constructor.setBody("{}"); helperClazz.addConstructor(constructor);
final StringBuffer sb = new StringBuffer(); sb.append("public Object create(java.sql.ResultSet rs) throws Exception {\n"); sb.append(entityClazz.getName()) .append(" obj = new ") .append(entityClazz.getName()) .append("();\n");
Field[] fArr = entityClazz.getFields();
for (Field f : fArr) { Column annoColumn = f.getAnnotation(Column.class);
if (annoColumn == null) { continue; }
String colName = annoColumn.name();
if (f.getType() == Integer.TYPE) { sb.append("obj.") .append(f.getName()) .append(" = rs.getInt(\"") .append(colName) .append("\");\n"); } else if (f.getType().equals(String.class)) { sb.append("obj.") .append(f.getName()) .append(" = rs.getString(\"") .append(colName) .append("\");\n"); } else { } }
sb.append("return obj;\n"); sb.append("}");
CtMethod cm = CtNewMethod.make( sb.toString(), helperClazz ); helperClazz.addMethod(cm); helperClazz.writeFile("C:/Data/Temp+Test/debug-java"); Class<?> javaClazz = helperClazz.toClass();
helperObj = (AbstractEntityHelper) javaClazz.newInstance(); _entityHelperMap.put(entityClazz, helperObj);
return helperObj; } }
|