import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MyLoveForYou { String love(); }
public class Love { @MyLoveForYou(love="吾爱亦吾心") private String love; public String getLove() { return love; } public void setLove(String love) { this.love = love; } //重写 toString() 方法。 @Override public String toString() { return "Love [love=" + love + "]"; } }
import java.lang.reflect.Field; public class ProcessAnnotation { private static Love love; //创建 love 实例 public static Love getLove(){ Class<?> clazz = Love.class; try { Field field = clazz.getDeclaredField("love"); field.setAccessible(true); MyLoveForYou myLoveForYou = field.getAnnotation(MyLoveForYou.class); String fieldLove = myLoveForYou.love(); try { love = (Love)clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } love.setLove(fieldLove); } catch (NoSuchFieldException | SecurityException e) { e.printStackTrace(); } return love; } }
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Test { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { //异常有点多,但是不用担心,其实只有三行代码。 Love love = ProcessAnnotation.getLove(); System.out.println(love.getLove()); System.out.println(love.toString()); } }
A brief explanation is as follows
A very simple annotation class is used here, using the two most basic meta-annotations (the meaning of meta-annotations is: modifies the class The properties are retained until runtime ).
Then you can use annotations. Simple use is actually very simple, just like the following.
@MyLoveForYou(love="My love is also my heart")
I emphasize the following. Simply using annotations is of no use. Annotations require special Tool processing, here defines a simple class for processing annotations (This class may require a little knowledge of reflection, but it doesn’t matter. If you just want to know the function of the annotations, you can leave it alone and just remember the usage): ProcessAnnotation
Usage: This class does one thing, assign the value to love as 我爱也我心.
The last step is to test. The toString() method is rewritten here, which looks more intuitive.
The above is the detailed content of Java annotation entry case code analysis. For more information, please follow other related articles on the PHP Chinese website!