1. 注解分为两种 : 内置注解(jdk自带的注解) 和 自定义注解()
@SuppressWarnings 在程序前面加上可以 在javac编译中去除警告
@Deprecated 带有标记的包,方法 ,字段 说明其过时
@Overricle 说明该方法是将父类的方法重写
2. 自定义注解
@SetTable(value="t_user")
public class User {
@SetName(value = "tina")
private String username;
@SetName(value = "12345")
private String password;
}
@Retention(RetentionPolicy.RUNTIME)
@interface SetTable {
String value();
}
public class UserTest {
public static void main(String[] args) throws ClassNotFoundException {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("select");
//利用注解和反射生成动态的sql语句
Class<?> forName = Class.forName("com.example.mayi.annotation.User");
//获取表名
String tableName = forName.getAnnotation(SetTable.class).value();
//获取该类下的成员变量的属性值
Field[] declaredFields = forName.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
Field declaredField = declaredFields[i];
declaredField.setAccessible(true);
String value = declaredField.getAnnotation(SetName.class).value();
//System.out.println(value);
if(i ==(declaredFields.length-1)){
stringBuffer.append(value+ " from "+tableName+" ");
}else {
stringBuffer.append(" "+value+" , ");
}
}
System.out.println(stringBuffer.toString());
}
}
@Retention(value = RetentionPolicy.RUNTIME)
@interface SetName{
String value();
}
网友评论