您的位置:首页 > 移动开发 > Android开发

[Android]annottation @NonNull and @interface

2017-12-20 16:52 531 查看
在看源码时,看到了  @NonNull , 它为 android 的 一种注释, 即JAVA Annotation, 用来注释参数,参数值不能为 null,不然 IDE 会发警告。

Java 从1.5开始提供了 Annotation (注释,标注),它用来修饰应用程序的元素(类,方法,属性,参数,本地变量,包、元数据),编译器将其与元数据一同存储在 class 文件中,运行期间通过 Java 的反射来处理对其修饰元素的访问。

Annotation 仅仅用来修饰元素,而不能影响代码的执行。只有通过其配套的框架或工具才能对其信息进行访问和处理。

protected void onSaveInstanceState(@NonNull Bundle outState) {

...

}

源码如下:

frameworks/base/core/java/android/annotation/NonNull.java

frameworks/support/annotations/src/android/support/annotation/NonNull.java

package android.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.SOURCE;

/**
* Denotes that a parameter, field or method return value can never be null.
* <p>
* This is a marker annotation and it has no specific attributes.
*
* @hide
*/
@Retention(SOURCE)
@Target({METHOD, PARAMETER, FIELD})
public @interface NonNull {
}


定义注解格式:
public @interface 注解名 {定义体}

@interface 是用来修饰 Annotation 的,请注意,它不是 interface。

使用@interface自定义注解时,这个关键字声明隐含了一个信息:它是自动继承了 java.lang.annotation.Annotation 接口,而不是声明了一个 interface,由编译程序自动完成其他细节。

在定义注解时,不能继承其他的注解或接口。

要想了解更多,可以查找“Java annottation”.

参考:
http://blog.csdn.net/qq_16628781/article/details/49337565 http://blog.csdn.net/icedream_hong/article/details/44103083
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android
相关文章推荐