您的位置:首页 > 编程语言 > Java开发

java注解简单实例

2015-08-10 10:49 459 查看
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();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: