1. 基本概念
注解,可定义在类上、方法上或变量上,来扩展注解对象的描述信息,就像打了符号般,以后在对这些信息进行解析时,有了这些注解,就可以做出判断并采取相应的解析过程。如有@Override注解的方法就需要在接口中或父类中存在,否则则报错;有@Autowire注解的,spring 框架就尝试去注入相应的对象。有了这些注解,我们就可以更灵活地处理代码。
1.1 注解的使用定义
如:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBName {
public String name() default "";
}
2. 使用场景
mybatis,spring框架的各种注解的使用。
3. 使用实例
一个粗糙的例子来练习注解的使用。该例子主要是来生成对一个bean的更新语句。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 表名注解
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DBName {
public String name() default "";
}
/**
* 主键注解
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Key {
public String name() default "";
}
/**
* 实体类
*/
@DBName(name="student")
public class Student {
@Key(name="id")
private String id;
private String password;
private String username;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* sql语句构造类
* @param <T>
*/
public class SqlCreator<T> {
public String createUpdateSql(T obj) throws IllegalArgumentException, IllegalAccessException{
Class class1 = obj.getClass();
String className = class1.getSimpleName().toLowerCase();
String tableName = null;
//获取表名
DBName dbTable = (DBName) class1.getAnnotation(DBName.class);
if(dbTable != null){
tableName = dbTable.name();
}else{
tableName = className;
}
//获取主键
Field[] fields = class1.getDeclaredFields();
String keyName = "";
for(Field field :fields){
field.setAccessible(true);
String fieldName = field.getName();
Annotation[] annotations = field.getAnnotations();
if(annotations.length < 1) continue;
if(annotations[0] instanceof Key){
Key key = (Key) annotations[0];
keyName = key.name();
if(keyName == null || keyName.equals("")) keyName = fieldName.toLowerCase();
break;
}
}
//获取要更新的字段及值
Map<String, Object> updateContent = new HashMap<String, Object>();
for(Field field:fields){
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
if(value != null){
updateContent.put(fieldName, value);
}
}
//构造语句
StringBuffer sb = new StringBuffer();
sb.append(String.format("update %s set ", tableName));
for(String fieldName:updateContent.keySet()){
String update = "";
Object value = updateContent.get(fieldName);
if(fieldName.equals(keyName) == false){
if(value instanceof String){
update = fieldName+" = '"+String.valueOf(value)+"',";
}else if(value instanceof Integer){
update = fieldName + " = "+(Integer)value+",";
}
sb.append(update);
}
}
sb.deleteCharAt(sb.length()-1); //去逗号
//加主键条件
sb.append(String.format(" where %s = '%s'", keyName,updateContent.get(keyName)));
return sb.toString();
}
}
/**
* 测试
*/
public class MainClass {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
Student s = new Student();
s.setPassword("password");
s.setId("id");
s.setUsername("name");
SqlCreator<Student> creator = new SqlCreator<Student>();
System.out.println(creator.createUpdateSql(s));
}
}
运行结果:
update student set password = 'password',username = 'name' where id = 'id'