您的位置:首页 > 编程语言 > Java开发

java 自定义annotation

2016-06-22 18:07 288 查看
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Inherited
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Column {
String value() default "";
}

 

 

   

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Inherited  //继承
@Target({ElementType.TYPE})  //TYPE 类 METHOD : 方法
@Retention(RetentionPolicy.RUNTIME) //运行时
@Documented
public @interface Table {
String value() default "";
}

 

@Table("tb_test")
public class TestDao {

@Deprecated
private String tt;

@Column("_id")
private String id;

@Column("_name")
private String name;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

 

 

 

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {

/**
* 通过注解组装查询条件,生成查询语句
*/
public static String assembleSqlFromObj(Object obj) {
Table table = obj.getClass().getAnnotation(Table.class);
StringBuffer sbSql = new StringBuffer();
String tableName = table.value();
sbSql.append("select * from " + tableName + " where 1=1 ");
Field[] fileds = obj.getClass().getDeclaredFields();
for (Field f : fileds) {
String fieldName = f.getName();
String methodName = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Column column = f.getAnnotation(Column.class);
if (column != null) {
Method method = obj.getClass().getMethod(methodName);
String value = (String) method.invoke(obj);
if (value != null && !value.equals("")) {
if (!isnum(column.value()) && !isnum(value)) {
// 判断参数是不是 in 类型参数 1,2,3
if (value.contains(",")) {
sbSql.append(" and " + column.value() + " in (" + value + ") ");
} else {
sbSql.append(" and " + column.value() + " like '%" + value + "%' ");
}
} else {
sbSql.append(" and " + column.value() + "=" + value + " ");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return sbSql.toString();

}

public static boolean isnum(String target){
if(target.toUpperCase().contains("id")){
return true;
}
if(target.matches("\\d+")){
return true;
}
return false;

}

}

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: