import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FiledRef
{
String fieldName();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableRef
{
String tableName();
}
@TableRef(tableName = "MobDevice")
public class ReflectTest
{
@FiledRef(fieldName = "ID")
private Long id;
@FiledRef(fieldName = "DEVICE_NAME")
private String name;
@FiledRef(fieldName = "DEVICE_CODE")
private String code;
public ReflectTest(Long id, String name, String code)
{
this.id = id;
this.name = name;
this.code = code;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
/**
* @description
* @author zhangml
* @date May 17, 2010 4:39:30 PM
* @param args
*/
public static void main(String[] args)
{
ReflectTest rt = new ReflectTest(new Long(1), "2", "3");
StringBuffer sql = new StringBuffer("");
buildSql(rt, sql);
System.err.println(sql);
}
public static void buildSql(Object obj, StringBuffer sb)
{
Class<? extends Object> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
if (clazz.isAnnotationPresent(TableRef.class))
{
TableRef tr = (TableRef) clazz.getAnnotation(TableRef.class);
sb.append("SELECT * FROM ");
sb.append(tr.tableName());
}
if (fields != null && fields.length > 0)
{
sb.append(" WHERE ");
for (Field field : fields)
{
try
{
Object value = field.get(obj);
if (value != null && field.isAnnotationPresent(FiledRef.class))
{
FiledRef fr = field.getAnnotation(FiledRef.class);
sb.append(fr.fieldName() + "=" + value);
sb.append(" AND ");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
int length = sb.length();
sb.delete(length-5, length);
}
}
}
执行结果:SELECT * FROM MobDevice WHERE ID=1 AND DEVICE_NAME=2 AND DEVICE_CODE=3
java Annotation 拼装SQL语句(转)
最新推荐文章于 2024-05-20 07:21:46 发布