注解从JDK自带注解到自定义注解的发展
发布日期:2021-05-10 02:45:00 浏览次数:22 分类:精选文章

本文共 2724 字,大约阅读时间需要 9 分钟。

1.@Override注解

用于重写父类的方法 或者是写接口实现类时用到该注解。

编写一个Test类测试一下,出现警告:run()方法已经过时。为什么呢?因为我在定义Animal接口时,在run()方法上添加了注解@Deprecation,表示方法已经过时,方法上有横线,使用时会有警告。

当然我们忽略警告,直接运行也是可以的,但如果有强迫症的同学呢,可以增加@SuppressWarnings来去掉警告:

也可以直接写为@SuppressWarnings(“all”)直接去掉所有类型的警告!!!

 

 

自定义注解(代码解析)

//用注解来修饰注解,规范注解可以加在哪里//  代表此@interface注解可以修饰方法  代表可以修饰构造方法   修饰属性          修饰类@Target({ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.PARAMETER,ElementType.TYPE})//  设置注解在什么时候起作用    Source代表源文件(没编译呢)     Class代表字节码文件(编译时)    Runtime代表运行时(运行时起效果就是这)@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {     String name();    //String name() default "";   当写为这时候,就可以不用在Demo类中写(name="")    String value();//    String[] shuzu();}
//@MyAnnotation@Repositorypublic class MyAnnotationDemo {//    @MyAnnotation    public MyAnnotationDemo(){    }    //1、当注解接口里没有属性方法时候,这里写 @MyAnnotation不会报错,当写了的时候就会报错,需要加上对应的value    @MyAnnotation(value = "abc",name="bank")    //或者写@MyAnnotation("abc")    //2、当参数为name时候,就得必须写@MyAnnotation(name = "abc")或@MyAnnotation(name = ""),必须有name=    //3、String name() default "";   当接口中写为这时候,就可以不用在Demo类中写(name="")    //4、写为数组时候,就为@MyAnnotation(shuzu = {"abc",name="bank"})    public void test(/*@MyAnnotation*/ int num){    }    public static void main(String[] args) {    }}

 

代码例子解析

@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface Test {}
public class TestDemo {    @Test    public void  test1(){        System.out.println("test1");    }    public void test2(){        System.out.println("test2");    }}
public class AnnotationTest {    public void process(TestDemo testDemo) throws Exception{        Class
clazz = TestDemo.class; Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { System.out.println(method.getName()); } } public void process1(TestDemo testDemo) throws Exception{ Class
clazz = TestDemo.class; Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { // 此方法是主只要有注解的方法 所以打印出来的为test1 if(method.isAnnotationPresent(Test.class)){ method.invoke(testDemo); } System.out.println(method.getName()); } } public static void main(String[] args) throws Exception{ TestDemo testDemo = new TestDemo(); AnnotationTest annotationTest = new AnnotationTest(); annotationTest.process(testDemo); System.out.println("========================="); annotationTest.process1(testDemo); //运行后可以获取所有方法的名字 }}

 

个性签名:一个人在年轻的时候浪费自己的才华与天赋是一件非常可惜的事情

        如果觉得这篇文章对你有小小的帮助的话,记得在左下角点个“👍”哦,博主在此感谢!

 

万水千山总是情,打赏5毛买辣条行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾! 

上一篇:MyBatis创建项目
下一篇:通俗来谈异常(不全)

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月28日 08时47分06秒