Java:利用注解执行特定的方法
Java中的注解是一门艺术,里面的学问不少,本实例介绍的是注解对方法的作用性
1. 新建一个注解类
package com.zhebie.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(RetentionPolicy.RUNTIME) //运行时有效
public @interface ThisAnnotations {
//声明一个无默认值的属性
public String nodefault() default "";
//value属性没有默认值
public String novalue();
//声明一个有默认值的属性
public String existdefault() default "havaonevalue";
}
2. 新建一个对象类(做测试使用)
package com.zhebie.annotation;
public class UseAnnotations {
private Integer id;
//private String password;
@ThisAnnotations(novalue="ThisAnnotations注解里的value属性")
public Integer getId() {
return id;
}
}
3. 新建一个测试对象
package com.zhebie.annotation;
import java.lang.reflect.Method;
import org.junit.Test;
public class UseAnnoTest {
@Test
public void annoTest() throws Exception {
//Class<?> cls = Class.forName("com.zhebie.annotation.ThisAnnotations");
Class<?> cls = UseAnnotations.class; //1.获取需要测试的类对象
Method mmethod = cls.getDeclaredMethod("getId"); //2.获取特定的方法
if(!mmethod.isAnnotationPresent(ThisAnnotations.class)) return; //3.判断是否有注解:如果没有就直接返回
ThisAnnotations annotation = mmethod.getAnnotation(ThisAnnotations.class); //4.获取在该方法上的注解
System.out.println("existdefault="+annotation.existdefault());
System.out.println("nodefault="+annotation.nodefault());
System.out.println("novalue="+annotation.novalue());
if("havaonevalue".equals(annotation.existdefault())) { //5.可以通过注解(如果有)做一些具体的执行语句
System.out.println("\n注解的作用:比如本条语句就是因为有了ThisAnnotations注解才会执行\n"
+ "而实际应用场景中会比较复杂,但其原理与本测试类并不矛盾");
}
}
}
- 演示动图