自定义注解
自定义一个java注解,用来注解到方法上面
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String[] value() default "张三";
}
public class Person {
@MyAnnotation(value = "lisi")
public void boy(String name){
System.out.println("boy name is "+ name);
}
@MyAnnotation(value = "zhangsan")
public void girl(String name){
System.out.println("girl name is " +name);
}
}
通过反射来获取注解
public class PersonAnnonationTest {
public static void main(String[] args) throws Exception{
Class> personClass = ClassLoader.getSystemClassLoader().loadClass("com.rookie.bigdata.annotation.Person");
Person personInstance = (Person)personClass.newInstance();
Method method = personClass.getMethod("boy", new Class[]{String.class});
method.invoke(personInstance,new Object[]{"张三"});
//获取注解上面的值
if(method.isAnnotationPresent(MyAnnotation.class)){
//获取上面的注解
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
//获取注解的值
String[] value = annotation.value();
for (String s : value) {
System.out.println(s);
}
}
}
}