编译时注解apt / kapt

本文介绍了注解在Java和Kotlin中的应用,包括元注解、注解分类(运行时和编译时)、APT和KAPT的工作原理。通过一个实例展示了如何使用编译时注解、APT和动态生成字节码实现类似ButterKnife的findViewById功能,包括声明注解、获取注解、动态生成字节码以及调用过程。最后,文章提到了利用反射在运行时调用编译时生成的静态方法。
摘要由CSDN通过智能技术生成

注解

一个注解允许你把额外的元数据关联到一个声明上。然后元数据就可以被相关的源代码工具访问,通过编译好的类文件或是在运行时,取决于这个注解是如何配置的。 --《Kotlin in Action》

注解(也被成为元数据)为我们在代码中添加信息提供了一种形式化的方法,使我们可以在稍后某个时刻非常方便地使用这些数据。 --《Thinging in Java》

在Java和Kotlin中声明注解的方式还是有些差异:

Java:
public @interface MyAnnotation {
}

public @interface MyAnnotation2{
    String value();
}

Kotlin:
annotation class MyAnnotation

annotation class MyAnnotation2(val value:String)

元注解

可以应用到注解类上的注解被称为元注解。

比较常见的元注解有@Target、@Retention

@Target(AnnotationTarget.ANNOTATION_CLASS)
@MustBeDocumented
public annotation class Target(vararg val allowedTargets: AnnotationTarget)
public enum class AnnotationTarget {
    /** Class, interface or object, annotation class is also included */
    CLASS,
    /** Annotation class only */
    ANNOTATION_CLASS,
    /** Generic type parameter (unsupported yet) */
    TYPE_PARAMETER,
    /** Property */
    PROPERTY,
    /** Field, including property's backing field */
    FIELD,
    /** Local variable */
    LOCAL_VARIABLE,
    /** Value parameter of a function or a constructor */
    VALUE_PARAMETER,
    /** Constructor only (primary or secondary) */
    CONSTRUCTOR,
    /** Function (constructors are not included) */
    FUNCTION,
    /** Property getter only */
    PROPERTY_GETTER,
    /** Property setter only */
    PROPERTY_SETTER,
    /** Type usage */
    TYPE,
    /** Any exp
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值