当前位置: 首页 > 后端技术 > Java

java注解_0

时间:2023-04-02 09:29:58 Java

记录自己使用注解的过程//Step1:定义注解@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public@interfaceSimpleAnnotation{Stringvalue();}//Step2:在方法中使用publicclassUseAnnotation{@SimpleAnnotation(value="testStringValue")publicvoidtestMethod(){}}//第三步:获取使用了哪些方法publicclassLogicMain{publicstaticvoidmain(String[]args){ClassuseAnnotationClass=UseAnnotation。班级;for(Methodmethod:useAnnotationClass.getMethods()){SimpleAnnotationannotation=method.getAnnotation(SimpleAnnotation.class);if(null!=annotation){System.out.println("方法名称:"+method.getName());System.out.println("值:"+annotation.value());}}}}输出结果:MethodName:testMethodvalue:testStringValue//Step1:Defineannotation@Inherited@Retention(RetentionPolicy.RUNTIME)public@interfaceMyAnnotation{Stringvalue()default"hello";}//第二步:在父类上使用,子类继承该类@MyAnnotationpublicclassPerson{}classStudentextendsPerson{}//第三步:获取publicclassTestAnnotation{publicstaticvoidmain(String[]args){Classclazz=Student.class;Annotation[]annotations=clazz.getAnnotations();for(Annotationannotations:annotations){System.out.println(annotation);}}}输出结果:@com.zcl.edu.annotation2.MyAnnotation(value="hello")