java注解反射简单实例

1、创建一个注解

package com.anno;

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

@Retention(RetentionPolicy.RUNTIME) // 表示注解在运行时依然存在
@Target(ElementType.METHOD) // 表示注解可以使用在方法上
public @interface CallAnnotation {

    String phone() default "某某";; // 表示注解须要一个参数,默认值为"某某"

}

 

2、创建一个person类,使用注解

package com.anno;


public class Person {

    public void call( String phone) {
        System.out.println("call=>"+phone);
    }
    
    
    @CallAnnotation
    public void callByAnnotationDefault(String phone){
        System.out.println("callByAnnotationDefault=>"+phone);
    }
    
    
    @CallAnnotation(phone = "张三")
    public void callByUserAnnotation(String phone){
        System.out.println("callUserAnnotation=>"+phone);
    }


}

 

 

3、测试注解

 

package com.anno;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestAnno {

    public static void main(String[] args)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        
        Person person = new Person(); //创建person对象
        Method[] methods = Person.class.getDeclaredMethods(); //得到所有方法
        for (Method meth : methods) {
            CallAnnotation annoTemp = null;

            annoTemp = meth.getAnnotation(CallAnnotation.class); //得到注解对象
            System.out.println("调用方法名称:" + meth.getName());
            System.out.println("注释的对象信息:" + annoTemp);
            if (annoTemp != null) { //如果注解对象不为空,将参数值设为注解的值
                meth.invoke(person, annoTemp.phone());
            } else {
                meth.invoke(person, "李四"); //如果注解对象为空,单独设置参数值
            }

            System.out.println();
        }
    }

}

 

 

 

 

转 :  https://www.cnblogs.com/2015android/p/4717348.html

 

posted @ 2020-11-05 11:14  与f  阅读(236)  评论(0编辑  收藏  举报