自定义注解
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); } }
标签:lang,java,自定义,value,public,import,注解,annotation From: https://www.cnblogs.com/chengxin1982/p/17015306.html