java 反射和注解的简单应用

来源:互联网 发布:网络授课教师招聘 编辑:程序博客网 时间:2024/06/03 00:08

简单的主键注解:

package com.bj.util;
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 PrimaryKey {
    
}

//下面是关联表的注解

package com.bj.util;


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 NonField {

}

//利用注解来拼接sql语句

public static String getUpdate(Object obj) throws IllegalArgumentException, IllegalAccessException{
Class<? extends Object> classzz = obj.getClass();
String sql = "update "+classzz.getSimpleName()+" set";
String sql2 = "";
String sql3 = " where ";
//获取字段
Field[] fields = classzz.getDeclaredFields();
for(Field f:fields){
f.setAccessible(true);//可以访问private字段的值
Object value = f.get(obj);
//如果该字段具备primaryKey注解
if(f.isAnnotationPresent(PrimaryKey.class)){
if(value instanceof String ){
sql3 +=f.getName()+"=' "+value+" ' ";
}else{
sql3 += f.getName()+" = "+value+" ";
}
}else if(!f.isAnnotationPresent(NonField.class)){//这里利用了NonField关联注解
if(value instanceof String){
  sql2 += f.getName() +"='"+value+"',";
  }else{
  sql2+=f.getName()+"="+value+", ";
  }
}
}
sql2 = sql2.substring(0,sql2.length()-1);
sql = sql+sql2+sql3;
return sql;
}

0 0