具体使用Java注解的方式

具体使用Java注解的方式

1.使用预定义注解: 预定义注解是Java提供的一些内置注解,可以直接在代码中使用。例如,@Override、@Deprecated、@SuppressWarnings等。

@Override
public void run() {
    // 重写父类的run()方法
    // ...
}

@Deprecated
public class OldClass {
    // ...
}

@SuppressWarnings("unchecked")
public List<SomeClass> getSomeList() {
    // ...
}

2.创建自定义注解: 如果想要自定义注解,需要使用@interface关键字,并指定注解的元素。

@Retention(RetentionPolicy.RUNTIME) // 指定注解保留到运行时
@Target(ElementType.METHOD) // 指定注解适用于方法
public @interface MyAnnotation {
    String value();
    int count() default 1;
}

3.然后在需要使用该注解的地方进行注解的引用,指定注解的元素值。

public class MyClass {
    @MyAnnotation(value = "example", count = 5)
    public void myMethod() {
        // ...
    }
}

4.在运行时,可以使用反射来获取注解的信息。

MyClass obj = new MyClass();
Method method = obj.getClass().getMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String value = annotation.value(); // 获取注解的元素值
int count = annotation.count();

demo

package com.lidaochen.test;

public class CJavaTest {
    public void eat()
    {
        System.out.println("我喜欢吃西瓜!");
    }
}
package com.lidaochen.test;

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.TYPE)
public @interface Pro {
    String className();
    String methodName();
}
package com.lidaochen.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.Properties;

@Pro(className = "com.lidaochen.test.CJavaTest", methodName = "eat")
public class CJavaDemo {
    public static void main(String[] args) throws Exception{
        // 1、获取该类的字节码对象
        Class cls = CJavaDemo.class;
        // 2、获取上边的注解对象
        Pro an = (Pro) cls.getAnnotation(Pro.class);
        // 3、调用注解对象中定义的抽象方法,获取返回值
        String className = an.className();
        String methodName = an.methodName();
        System.out.println(className);
        System.out.println(methodName);
        // 4、加载该类进内存
        Class mJavaTest = Class.forName(className);
        // 创建对象
        Object obj = mJavaTest.newInstance();
        // 获取方法对象
        Method method = mJavaTest.getMethod(methodName);
        // 执行方法
        method.invoke(obj);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值