Java/Android Annotation注解/注入(二)

版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/86615485

Java/Android Annotation注解注入(二)

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

@Target(ElementType.METHOD) //约束条件。只能限定注解修饰在函数方法。
@Retention(value = RetentionPolicy.RUNTIME) //运行时。
public @interface Info {
    int id() default 0;
    String name() default "zhang";
    String password() default "123";
}
public class User {

    @Info(id = 1, name = "zhangphil", password = "123456")
    public void initUser() {

    }
}
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Method method = null;
        try {
            method = User.class.getMethod("initUser", null);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        //是否存在Info的注解?
        if (method.isAnnotationPresent(Info.class)) {
            Info info = method.getAnnotation(Info.class);

            //打印在该method上的注解Info信息。
            System.out.println(info);

            System.out.println(info.id());
            System.out.println(info.name());
            System.out.println(info.password());
        }
    }
}

运行输出:

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/86615485