annotations的学习

注解编写的过程中,需要明确两点:
1、注解使用的位置,Target(Elementyple."选择有多种" )
(1、)TYPE可以使用在类、接口、注解等位置
···· (2、)FILED字段
(3、)METHOD方法
(4、)PARAMETER参数
(5、)ANNOTATION_TYPE注解
2、注解的作用时间@Retention(RetentionPolicy."选择有多种")
(1、)CLASS class文件
(2、)RUNTIME运行
(3、)SOURCE源码
例子-------------------------------------------------------------------取自java编程思想代码学习内容
eg:
1、
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLInteger {
String name() default "";
Constraints constraints() default @Constraints;
}
2、
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLInteger {
String name() default "";
Constraints constraints() default @Constraints;
} ///:~

3、记录一个例子 这是怎么获取注解的例子
for(String className : args) {
Class<?> cl = Class.forName(className);
DBTable dbTable = cl.getAnnotation(DBTable.class);
if(dbTable == null) {
System.out.println(
"No DBTable annotations in class " + className);
continue;
}
String tableName = dbTable.name();
// If the name is empty, use the Class name:
if(tableName.length() < 1)
tableName = cl.getName().toUpperCase();
List columnDefs = new ArrayList();
for(Field field : cl.getDeclaredFields()) {
String columnName = null;
Annotation[] anns = field.getDeclaredAnnotations();
if(anns.length < 1)
continue; // Not a db table column
if(anns[0] instanceof SQLInteger) {
SQLInteger sInt = (SQLInteger) anns[0];
// Use field name if name not specified
if(sInt.name().length() < 1)
columnName = field.getName().toUpperCase();
else
columnName = sInt.name();
columnDefs.add(columnName + " INT" +
getConstraints(sInt.constraints()));
}
if(anns[0] instanceof SQLString) {
SQLString sString = (SQLString) anns[0];
// Use field name if name not specified.
if(sString.name().length() < 1)
columnName = field.getName().toUpperCase();
else
columnName = sString.name();
columnDefs.add(columnName + " VARCHAR(" +
sString.value() + ")" +
getConstraints(sString.constraints()));
}
StringBuilder createCommand = new StringBuilder(
"CREATE TABLE " + tableName + "(");
for(String columnDef : columnDefs)
createCommand.append("\n " + columnDef + ",");
// Remove trailing comma
String tableCreate = createCommand.substring(
0, createCommand.length() - 1) + ");";
System.out.println("Table Creation SQL for " +
className + " is :\n" + tableCreate);
}
}

代码写了几遍哈哈哈感觉深入理解了,防止以后遗忘找回容易点所以复制过来了
cl.getDeclareMethod();是获取自身的Method方法
cl.getMethod();是获取自身以及继承过来的Method

最后,所有的加有Declare的都是自身,不加就是获取所有

posted @ 2019-10-10 17:31  堕落先锋  阅读(217)  评论(0编辑  收藏  举报