java自定义注解

自定义注解

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.FIELD)
public @interface ToLowerCase {
    boolean ignoreCase() default false;
}

调用

package zj;


import org.aspectj.lang.Aspects;

import java.lang.reflect.Field;

public class MyClass {
    @ToLowerCase(ignoreCase=true)
    public String field1;

    @ToLowerCase(ignoreCase=false)
    public String field2;

    public void convertToLowerCase() {
        for (Field field : this.getClass().getDeclaredFields()) {
            ToLowerCase annotation = field.getAnnotation(ToLowerCase.class);
            if (annotation != null) {
                try {
                    field.setAccessible(true);
                    String value = (String) field.get(this);
                    if (value != null) {
                        if (annotation.ignoreCase()) {
                            value = value.toLowerCase();
                        }
//                        else {
//                            value = value.toLowerCase(Locale.ENGLISH);
//                        }
                        field.set(this, value);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.field1 = "HELLO";
        obj.field2 = "WORLD";
        obj.convertToLowerCase();

        System.out.println(obj.field1 + obj.field2);
    }

}

 

posted @ 2022-12-30 16:55  谭志宇  阅读(18)  评论(0编辑  收藏  举报