java Annotation

原创
2016/05/20 14:19
阅读数 109

概念:

  • 内置注解:@Override(覆盖),@Deprecated(定义过期方法),@SuppressWarnings(消除警告)...

  • 元注解(用于定义注解):@Target,@Retention...

  • 自定义注解:用户自己定义

  • TableName.java

@Target(value={ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TableName {
	String value();
}
  • TableField.java
@Target(value={ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface TableField {
	String columnName();
	String type();
	int length();
}
  • StudentEntity.java
@TableName(value="student")
public class StudentEntity {
	@TableField(columnName="id",type="int",length=10)
	private int id;
	@TableField(columnName="name",type="varchar",length=255)
	private String name;
	@TableField(columnName="age",type="int",length=10)
	private int age;
}
  • EntityParser.java
public class EntityParser {	
	public static void main(String[] args) {
		try {
			Class clazz = Class.forName("com.icngor.annotation.StudentEntity");
		
			TableName tableName= (TableName)clazz.getAnnotation(TableName.class);
			System.out.println(tableName.value());
			
			Field field = clazz.getDeclaredField("name");
			TableField annotation = field.getAnnotation(TableField.class);
			System.out.println(annotation.columnName()+"=="+annotation.type()+"=="+annotation.length());
			
		} catch (Exception e) {		
			e.printStackTrace();
		}		
	}
}
展开阅读全文
加载中

作者的其它热门文章

打赏
2
1 收藏
分享
打赏
0 评论
1 收藏
2
分享
返回顶部
顶部