java注解概念使用及Demo

java注解

概念

Java提供了一种原程序中的元素关联任何消息和任何元数据的途径和方法,即注解

java中的常见注解

@Override
@Deprecated
@Suppvisewarnings

第三方注解

  1. Spring @Autowired @Service @Repository
  2. Mybatis @InsertProvider @UpdateProvider @Options

元注解

@Target注解 作用域控制

/** Class, interface (including annotation type), or enum declaration */
TYPE,

/** Field declaration (includes enum constants) */
FIELD,

/** Method declaration */
METHOD,

/** Formal parameter declaration */
PARAMETER,

/** Constructor declaration */
CONSTRUCTOR,

/** Local variable declaration */
LOCAL_VARIABLE,

/** Annotation type declaration */
ANNOTATION_TYPE,

/** Package declaration */
PACKAGE,

/**
 * Type parameter declaration
 *
 * @since 1.8
 */
TYPE_PARAMETER,

/**
 * Use of a type
 *
 * @since 1.8
 */
TYPE_USE

@Retention注解的生命周期

 /**
 * Annotations are to be discarded by the compiler.
 * 注解只在源码中存在,编译成.class就不存在了 
 */
SOURCE,

/**
 * Annotations are to be recorded in the class file by the compiler
 * but need not be retained by the VM at run time.  This is the default
 * behavior.
 * 注解在源码和.class文件中都存在 jdk自带的注解都属于编译时注解 
 */
CLASS,

/**
 * Annotations are to be recorded in the class file by the compiler and
 * retained by the VM at run time, so they may be read reflectively.
 * 运行阶段还起作用,设置可以影响代码运行逻辑@Autowired
 * @see java.lang.reflect.AnnotatedElement
 */
RUNTIME

@Inherited允许子类继承 标识性注解

@Documented生成javaDoc时会包含注解 标识性注解

自定义注解

元注解

使用@interface关键字定义注解

成员:
以无参无异常方式声明 可以用default给成员指定一个默认值
成员类型是受限制的:java基本数据类型 + String Class Annoatation Enumeration
如果注解只有一个成员,则成员名为value(),在使用是可以忽略成员名和赋值好(=)
注解类可以没有成员,没有成员则称为标识注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface TestAnnoation {
    String desc();
    int visted();
    String comment() default "test";
}

使用注解

@<注解名>(<成员名1>=<成员值1>,<成员名2>=<成员名2>,…)

@TestAnnoation(desc="ttttest",visted=1)
public class TestDomain {

}

解析注解

概念:通过反射获取类 函数或成员上的运行时注解信息,从而实现动态控制程序运行的逻辑

注解应用demo

定义注解

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Column {
    String value();
}

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Table {
    String value();
}

获取注解,定义注解要进行的操作

public class SqlUtil {
    public static String getSql(Object o){
        StringBuilder result = new StringBuilder();
        //1.获取class
        Class c = o.getClass();
        //2.获取table名字 即注解的value
        boolean isTableAnnotation = c.isAnnotationPresent(Table.class);
        if(!isTableAnnotation){
            return null;
        }
        Table t = (Table) c.getAnnotation(Table.class);
        String tableName = t.value();
        result.append("select * from ").append(tableName).append(" where 1 = 1");
        //3.获取字段名字
        Field[] declaredFields = c.getDeclaredFields();
        for (Field field : declaredFields) {
            //处理每个字段对应的sql
            //拿到字段名 看是不是column
            boolean isColumnAnnotation = field.isAnnotationPresent(Column.class);
            if(!isColumnAnnotation){
                continue;
            }
            Column colum = field.getAnnotation(Column.class);
            String columnName = colum.value();
            //拿到字段的值
            String fieldName = field.getName();
            String getMethodName = "get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
            Object fieldValue = null;
            try {
                Method method = c.getMethod(getMethodName);
                fieldValue = method.invoke(o);
            } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //拼装sql
            if(fieldValue == null || (fieldValue instanceof Integer && (Integer)fieldValue == 0)){
                continue;
            }
            result.append(" and ").append(fieldName).append("=");
            if(fieldValue instanceof String){
                result.append("'").append(fieldValue).append("'");
            }else if(fieldValue instanceof Integer){
                result.append(fieldValue);
            }else{
                //TODO 扩展其他类型
            }

        }
        return result.toString();
    };
}

应用注解,应用操作

public class Test {
    public static void main(String[] args) {
        User user = new User();
        user.setName("helloworld");
        user.setAge(1);
        String sql = SqlUtil.getSql(user);
        System.out.println(sql);
    }
}
//output
//select * from user where 1 = 1 and name='helloworld' and age=1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值