本文主要介绍如何使用Java运行时级别的注解配合反射来搭建框架,以下是构建sql表的简单例子,阐明了搭建运行时框架的方法
1.定义两个运行时注解,分别作用于类和字段表示表名和列名
2.定义存储列的模型NameAndType
3.定义javabea 和数据库之间的关系映射
4.通过反射定义工具类,定义动态获取表名,获取列相关信息和组装SQL
---运行结果如下:
1.定义两个运行时注解,分别作用于类和字段表示表名和列名
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
String name();
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
String name();
}
2.定义存储列的模型NameAndType
public class NameAndType {
private String name;
private String type;
public NameAndType()
{
}
public NameAndType(String type, String name)
{
this.type = type;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
3.定义javabea 和数据库之间的关系映射
@Table(name="BeanTable")
public class Bean {
@Column(name="field") //注解@Colomn 具体实现接下来会讲
int field;
@Column(name="description")
String description;
}
4.通过反射定义工具类,定义动态获取表名,获取列相关信息和组装SQL
public class Utils {
private static String getTableName(Class<?> clazz)
{
String name = null;
if(clazz.isAnnotationPresent(Table.class))
{
Table table = clazz.getAnnotation(Table.class);
name = table.name();
}
return name;
}
private static List<NameAndType> getColumns(Class<?> clazz)
{
List<NameAndType> list = new ArrayList<>();
Field[] fields = clazz.getDeclaredFields();
if(fields != null)
{
for(Field field : fields)
{
if(field.isAnnotationPresent(Column.class))
{
Column column = field.getAnnotation(Column.class);
String name = column.name();
String type = null;
if(int.class.isAssignableFrom(field.getType()))
{
type = "integer";
}
else if(String.class.isAssignableFrom(field.getType()))
{
type = "text";
}
else
{
throw new RuntimeException("unsupport type :" + field.getType().getSimpleName());
}
list.add(new NameAndType(type, name));
}
}
}
return list;
}
public static String createTable(Class<?> bean) {
String tableName = getTableName(bean);
List<NameAndType> columns = getColumns(bean);
if (tableName != null && !tableName.equals("") && !columns.isEmpty()) {
StringBuilder createTableSql = new StringBuilder("create table ");
//加表名
createTableSql.append(tableName);
createTableSql.append("(");
//加表中字段
for (int i = 0; i < columns.size(); i++) {
NameAndType column = columns.get(i);
createTableSql.append(column.getName());
createTableSql.append(" ");
createTableSql.append(column.getType());
// 追加下一个字段定义前需要添加逗号
if (i != columns.size() - 1) {
createTableSql.append(",");
}
}
createTableSql.append(")");
return createTableSql.toString();
}
return null;
}
}
public class Test {
public static void main(String[] args)
{
System.out.println(Utils.createTable(Bean.class));
}
}
---运行结果如下:
create table BeanTable(field integer,description text)