/**
* @version 1.0 2016-09-25
* @author Administrator
* @demonstrate 通过反射获取类。函数或成员上的运行时注解信息,从而实现动态控制程序运行
*
*/
package AnnotationTest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static String Query(Filter f)
{
StringBuilder sb=new StringBuilder();
Class c=f.getClass();
boolean exists=c.isAnnotationPresent(Table.class);
if(!exists)
return null;
Table t=(Table) c.getAnnotation(Table.class);
String tableName=t.value();
sb.append("select * from ").append(tableName).append("where 1=1");
Field[] fArray=c.getDeclaredFields();
for(Field filed : fArray)
{
boolean fExists=filed.isAnnotationPresent(Column.class);
if(!fExists)
continue;
Column column=filed.getAnnotation(Column.class);
String columnName=column.value();
String filedName=filed.getName();
String getMethodName="get"+filedName.substring(0, 1)
.toUpperCase()+filedName.substring(1);
Object filedValue=null;
try {
Method getMethod=c.getMethod(getMethodName);
try {
filedValue=getMethod.invoke(f, null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
} catch (SecurityException | NoSuchMethodException e) {
e.printStackTrace();
}
if(filedValue==null || filedValue instanceof Integer && (Integer)filedValue==0)
continue;
sb.append(" and ").append(filedName).append("=").append(filedValue);
}
return sb.toString();
}
public static void main(String[] args) {
Filter f1=new Filter();
f1.setId(12);
f1.setUserName("大白晓敏");
Filter f2=new Filter();
f2.setAge(21);
f2.setId(11);
Filter f3=new Filter();
f3.setUserName("小夏");
String sql1=Query(f1);
String sql2=Query(f2);
String sql3=Query(f3);
System.out.println(sql1);
System.out.println(sql2);
System.out.println(sql3);
}
}
package AnnotationTest;
@Table("user")
public class Filter {
@Column("id")
private int id;
@Column("user_name")
private String userName;
@Column("age")
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package AnnotationTest
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
String value()
}
package AnnotationTest;
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 Table {
String value();
}