注解初定义
程序员文章站
2022-07-08 10:25:10
...
1.定义
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 SampleAnnotation {
//注解名称是SampleAnnotation,需要用@interface定义注解
//方法
String value();
}
2. 使用
public class SampleAnnatationUser {
//这些值会被注解的value方法得到
@SampleAnnotation("oh my god ,i put a value in it")
public void use() {
System.out.println("success,i use");
}
public void notUse() {
System.out.println("fail,i am not use");
}
}
3.实现,无反射不注解
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class SampleMain {
public static void main(String[] args) {
SampleAnnatationUser sampleAnnatationUser = new SampleAnnatationUser();
for (Method method : sampleAnnatationUser.getClass().getMethods()) {
if (method.isAnnotationPresent(SampleAnnotation.class)) {
try {
SampleAnnotation annotation = method.getAnnotation(SampleAnnotation.class);
System.out.println(annotation.value());
method.invoke(sampleAnnatationUser, null);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
4.结果
oh my god ,i put a value in it
success,i use
上一篇: 简单利用java反射 理解注解的作用
下一篇: (三) 标准注解