注解例子
来源:互联网 发布:网络流行用语 编辑:程序博客网 时间:2024/06/06 12:46
直接上代码
接口
package annotation; import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target; /** * 自定义注解,用来配置方法 * @author 哈哈 */ @Retention(RetentionPolicy.RUNTIME) // 表示注解在运行时依然存在 @Target(ElementType.METHOD) // 表示注解可以被使用于方法上 public @interface SayHiAnnotation { String paramValue() default "哈哈"; // 表示我的注解需要一个参数 名为"paramValue" 默认值为"哈哈" }
SayHiEmlement类
package element; import annotation.SayHiAnnotation; /** * 要使用SayHiAnnotation的元素所在类 * 由于我们定义了只有方法才能使用我们的注解,我们就使用多个方法来进行测试 * @author 哈哈 */ public class SayHiEmlement { // 普通的方法 public void SayHiDefault(String name){ System.out.println("Hi, " + name); } // 使用注解并传入参数的方法 @SayHiAnnotation(paramValue="Jack") public void SayHiAnnotation(String name){ System.out.println("Hi, " + name); } // 使用注解并使用默认参数的方法 @SayHiAnnotation public void SayHiAnnotationDefault(String name){ System.out.println("Hi, " + name); } }
测试类
package Main; import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import element.SayHiEmlement;import annotation.SayHiAnnotation; public class AnnotionOperator { public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException { SayHiEmlement element = new SayHiEmlement(); // 初始化一个实例,用于方法调用 Method[] methods = SayHiEmlement.class.getDeclaredMethods(); // 获得所有方法 for (Method method : methods) { SayHiAnnotation annotationTmp = null; if((annotationTmp = method.getAnnotation(SayHiAnnotation.class))!=null) // 检测是否使用了我们的注解 method.invoke(element,annotationTmp.paramValue()); // 如果使用了我们的注解,我们就把注解里的"paramValue"参数值作为方法参数来调用方法 else method.invoke(element, "Rose"); // 如果没有使用我们的注解,我们就需要使用普通的方式来调用方法了 } } }
- 注解例子
- 注解 例子
- OpenCV SURF例子注解
- spring mvc注解例子
- OpenCV SURF例子注解
- spring mvc注解例子
- spring mvc注解例子
- spring_mvc注解例子
- springmvc注解例子
- spring mvc注解例子
- Spring 注解 小例子
- Spring 注解 小例子
- spring mvc注解例子
- 注解 小例子
- spring mvc注解例子
- JAVA注解简单例子
- java 自定义注解例子
- struts2 注解例子
- 读取文件并追加
- Android 滑动效果入门篇(一)—— ViewFlipper
- Android窗口管理服务WindowManagerService的简要介绍
- hbase测试压缩效果报告
- JDK配置环境变量
- 注解例子
- 高级会计师资格考试成绩合格证在全国范围内几年有效
- 安装Ecshop首页出现报错常见的问题解决办法
- 择夫
- cin,cout的加速
- VS2010 LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- oracle 审计
- Linux Kernel Porting CPU 方法概要
- 1018. 锤子剪刀布 (20) PAT+运行超时