Java注解的使用

Main

public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    
    Class<MyReflect> clazz = MyReflect.class;
    Constructor<MyReflect> constructor = clazz.getConstructor();
    MyReflect myReflect = constructor.newInstance();
    
    Field[] fields = clazz.getFields();
    for(Field field : fields) {
        MyAnnotation myAnnotation = field.getAnnotation(MyAnnotation.class);
        String val = myAnnotation.value();
        String fieldName = field.getName();
        String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        Method method = clazz.getMethod(methodName, String.class);
        method.invoke(myReflect, val);
    }
    
    System.out.println(myReflect);
}

MyReflect

public class MyReflect {

    @MyAnnotation("zhangsan")
    public String name;

    @MyAnnotation("18")
    public String age;

    @MyAnnotation("男")
    public String sex;

    @Override
    public String toString() {
        return "MyReflect{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

}

MyAnnotation

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {

    String value();

}
### Java注解的用法 Java注解是一种用于标记代码元素(如类、方法、字段等)的元数据工具。它们不会直接影响程序的功能,但在编译期或运行时可以通过特定工具或框架来解析这些注解并执行相应的操作。 #### 1. 注解的基本语法 注解以`@`符号开头,紧随其后的是注解名称。例如: ```java @Override public void myMethod() { // 方法体 } ``` 上述例子展示了内置注解`@Override`的应用场景,表示该方法重写了父类的方法[^2]。 #### 2. 使用自定义注解 除了内置注解外,还可以创建自己的注解。以下是定义和使用自定义注解的一个简单示例: ##### 定义注解 ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; // 设置注解的作用范围为方法 @Target(ElementType.METHOD) // 设置注解保留策略为运行时可见 @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation { String value(); // 注解属性 } ``` ##### 应用注解 ```java public class MyClass { @MyCustomAnnotation(value = "This is a custom annotation example.") public void annotatedMethod() { System.out.println("Annotated method called."); } } ``` 通过这种方式,可以在指定位置应用自定义注解,并为其设置属性值[^5]。 #### 3. 处理注解 为了在运行时获取注解的信息,通常需要借助反射机制。下面是一个简单的例子展示如何读取注解的内容: ```java import java.lang.reflect.Method; public class AnnotationProcessor { public static void main(String[] args) throws Exception { Class<MyClass> clazz = MyClass.class; for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(MyCustomAnnotation.class)) { // 检查是否有注解 MyCustomAnnotation annotation = method.getAnnotation(MyCustomAnnotation.class); System.out.println("Found annotation with value: " + annotation.value()); } } } } ``` 这段代码利用了反射技术遍历目标类的所有方法,并检测是否存在指定的注解。如果存在,则提取其中的数据[^3]。 #### 4. 可重复注解Java 8开始支持在同一地方多次声明相同类型的注解。这种特性被称为“可重复注解”。要实现这一点,需满足两个条件:一是容器注解;二是启用`@Repeatable`元注解[^4]。 示例如下: ```java import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @interface SingleAnnotation {} @Repeatable(ContainerAnnotation.class) @Retention(RetentionPolicy.RUNTIME) @interface RepeatedAnnotations {} @Retention(RetentionPolicy.RUNTIME) @interface ContainerAnnotation { RepeatedAnnotations[] value(); } class Example { @RepeatedAnnotations("First") @RepeatedAnnotations("Second") void test() {} } ``` 以上代码片段说明了一个典型的可重复注解的设计模式及其实际运用方式。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值