java注解学习

2018-03-25  本文已影响0人  Lonelyyy

1.java自带的三种默认注解

2.创建自定义注解

java定义了4种元注解用于创建自定义注解

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;
}
上一篇 下一篇

猜你喜欢

热点阅读