Java注解实例

目录

 

 

理论

例子


 

理论

注解的作用范围:@Target

生命周期:@Retention

作用范围:包、类、字段、方法、方法的参数、局部变量

生命周期:源文件SOURCE、编译CLASS、运行RUNTIME

 

例子

这里来一个简单的实例(本实例来源与mooc网,本人只是抄了一遍,和进行了简单的修改,在此感谢下mooc的老师)

程序运行截图如下:

程序结构如下:

Java注解实例_第1张图片

Column.java

package my;

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();
}

Filter.java

package my;

@Table("user")
public class Filter {
	
	@Column("id")
	private int id;
	
	@Column("user_name")
	private String userName;
	
	@Column("nick_name")
	private String nickName;
	
	@Column("age")
	private int age;
	
	@Column("city")
	private String city;
	
	@Column("email")
	private String email;
	
	@Column("mobile")
	private String mobile;

	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 String getNickName() {
		return nickName;
	}

	public void setNickName(String nickName) {
		this.nickName = nickName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
}

Table.java

package my;

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();
}

Test.java

package my;

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

public class Test {

	public static void main(String[] args) {
		
		Filter f1 = new Filter();
		f1.setId(10);
		
		Filter f2 = new Filter();
		f2.setUserName("lucy");
		
		Filter f3 = new Filter();
		f3.setEmail("[email protected], [email protected], [email protected]");
		
		String sql1 = query(f1);
		String sql2 = query(f2);
		String sql3 = query(f3);
		
		System.out.println(sql1);
		System.out.println(sql2);
		System.out.println(sql3);
	}
	
	private static String query(Filter f) {
		
		StringBuilder sb = new StringBuilder();
		
		//1. 获取到注解
		@SuppressWarnings("rawtypes")
		Class c = f.getClass();
		//2. 获取table的名字
		@SuppressWarnings("unchecked")
		boolean exists =c.isAnnotationPresent(Table.class);
		if(!exists) {
			
			return null;
		}
		
		@SuppressWarnings("unchecked")
		Table t = (Table)c.getAnnotation(Table.class);
		String tableName = t.value();
		sb.append("select * from ").append(tableName).append(" where 1 = 1");
		
		//3. 遍历所有的字段
		Field[] fArray = c.getDeclaredFields();
		for(Field field : fArray) {
			
			//4. 处理每个字段对应的sql
			//4.1 拿到字段名
			boolean fExists = field.isAnnotationPresent(Column.class);
			if(!fExists) {
				
				continue;
			}
			
			Column column = field.getAnnotation(Column.class);
			@SuppressWarnings("unused")
			String columnName = column.value();
			//4.2 拿到字段的值,用反射得到字段
			String filedName = field.getName();
			String getMethodName = "get" + filedName.substring(0, 1).toUpperCase() +
					filedName.substring(1);
			//通过反射取得值
			Object fieldValue = null;
			try {
				@SuppressWarnings("unchecked")
				Method getMethod = c.getMethod(getMethodName);
				fieldValue = getMethod.invoke(f);
			} 
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//4.3 拼装sql
			if(fieldValue == null ||(fieldValue instanceof Integer &&(Integer)fieldValue == 0)) {
				
				continue;
			}
			
			sb.append(" and ").append(filedName);
			if(fieldValue instanceof String) {
				
				if(((String)fieldValue).contains(",")) {
					
					String[] values = ((String)fieldValue).split(",");
					sb.append(" in(");
					for(String v : values) {
						
						sb.append("'").append(v).append("'").append(",");
					}
					sb.deleteCharAt(sb.length() - 1);
					sb.append(")");
				}
				else {
						
						sb.append("=").append("'").append(fieldValue).append("'");
					}
			}
			else if(fieldValue instanceof Integer) {
				
				sb.append("=").append(fieldValue);
			}
		}
		
		return sb.toString();
	}
}

这里我对注解的感悟,感觉是一个flag,通过这个flag,可以为每一个类,类中成员,标识一个项目需要的东西。

 

你可能感兴趣的:(Java)