自定义注解类和使用

自定义注解类和使用

自定义注解类

ElementType.TYPE:Class, interface (including annotation type), or enum declaration
ElementType.FIELD:Field declaration
ElementType.METHOD:Method declaration
ElementType.PARAMETER:Formal parameter declaration

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnoTableName {
	String value() default "";
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnoFieldColumn {
	String value() default "";
}

使用注解类

@AnnoTableName("T_STUDENT")
public class AnnoStudent {
	@AnnoFieldColumn("NAME")
	private String name;
	
	@AnnoFieldColumn("POST_ADDRESS")
	private String postAddress;

	private Integer gender;
	...省略get set
}
public class Demo01 {
	@Test
	public void test01() {
		AnnoStudent annoStudent = new AnnoStudent();
		annoStudent.setName("小明");
		annoStudent.setPostAddress("wu");
		String selectSql = getSelectSql(annoStudent);
		System.err.println(selectSql);
		// select NAME, POST_ADDRESS from T_STUDENT where 1=1 and NAME=小明 and POST_ADDRESS=wu
	}
	public static String getSelectSql(AnnoStudent annoStudent) {
		Class<? extends AnnoStudent> clazz = annoStudent.getClass();
		AnnoTableName annotationTable = clazz.getAnnotation(AnnoTableName.class);
		if (annotationTable == null) {
			throw new RuntimeException("参数有错!");
		}
		Field[] fieldArr = clazz.getDeclaredFields();
		String columnPart = "";
		String wherePart = " where 1=1";
		for (int i = 0; i < fieldArr.length; i++) {
			Field field = fieldArr[i];
			AnnoFieldColumn annotationField = field.getAnnotation(AnnoFieldColumn.class);
			if (annotationField == null) {
				continue;
			}
			String valueField = annotationField.value();
			if (i == 0) {
				columnPart += valueField;
			} else {
				columnPart += ", " + valueField;
			}
			try {
				field.setAccessible(true);
				Object object = field.get(annoStudent);
				if (object != null) {
					wherePart += " and " + valueField + "=" + object;
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		StringBuffer sb = new StringBuffer();
		sb.append("select ");
		String valueTable = annotationTable.value();
		sb.append(columnPart + " from " + valueTable + wherePart);
		return sb.toString();
	}
}
发布了95 篇原创文章 · 获赞 4 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_26264237/article/details/103108927