1.java自带的三种默认注解
- @Override,表示当前的方法定义将覆盖超类中的方法。
- @Deprecated,使用了注解为它的元素编译器将发出警告,因为注解@Deprecated是不赞成使用的代码,被弃用的代码。
- @SuppressWarnings,关闭不当编译器警告信息。
2.创建自定义注解
java定义了4种元注解用于创建自定义注解
-
@Target,注解作用的对象,取值(ElementType)有以下几类
CONSTRUCTOR:用于描述构造器
FIELD:用于描述域
LOCAL_VARIABLE:用于描述局部变量
METHOD:用于描述方法
PACKAGE:用于描述包
PARAMETER:用于描述参数
TYPE:用于描述类、接口(包括注解类型) 或enum声明
java1.8之后加入了TYPE_PARAMETER和TYPE_USE,用于方法参数以及类的使用,详见ElementType.java -
@Retention,注解的作用范围,RetentionPolicy类型有3种
SOURCE:在源文件中有效(即源文件保留)
CLASS:在class文件中有效(即class保留)
RUNTIME:在运行时有效(即运行时保留)
一般来说,注解是结合反射一起用的,所以RetentionPolicy选择RUNTIME -
Document,将注解包含在Javadoc中
-
@Inherited,允许子类继承父类中的注解
3.举例
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String value() default "";
}
public class MyObject {
@TestAnnotation(value = "testObject")
public String getName() {
return "No name";
}
}
import android.util.Log;
import java.lang.reflect.Method;
public class PrintResult {
public void print() {
String CLASS_NAME = "com.example.myapplication.MyObject";
try {
Class testClass = Class.forName(CLASS_NAME);
Method method = testClass.getMethod("getName");
if (method.isAnnotationPresent(TestAnnotation.class)) {
TestAnnotation annotation = method.getAnnotation(TestAnnotation.class);
Log.d("print", "" + annotation.value());
}
} catch (ClassNotFoundException ex) {
} catch (NoSuchMethodException nex) {
}
}
}
输出结果:
D/print: testObject
4.理解注解及其使用
注解相当于给作用的对象附加了一些额外的信息,扩展性好,而且也比较方便阅读
例如使用Gson的使用也会用到Gson中定义的注解,我们把json转换成对应的类,但是json中的一些字段不太适合直接作为java的字段命名,所以可以使用SerializedName来建立json字段与java字段的映射关系
"basic": {
"city":"广州"
"id":"1"
}
@SerializedName("basic")
public class WeatherBasic {
@SerializedName("city")
public String cityName;
@SerializedName("id")
public String weatherId;
}
网友评论