前几天看到注解这块,反正也没事,就当成自己学习,慢慢写注解,从底层写起,我也是个小吧,不足的地方强大家谅解
先是自己定义注解,比如我定义的注解有两个,一个是@longin,一个是@qw,代码如下
@Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) @Target(value={java.lang.annotation.ElementType.METHOD}) public @interface longin { //使用时候是@login String value() default "没改变value"; String hh() default "没改变hh"; } @Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME) @Target(value={java.lang.annotation.ElementType.METHOD}) @interface qw { //使用时候是@qw String value() default "loginaction"; String hh() default "COM.fanpeng.zhujie.ffs";这样,我们就定义了两个注解,现在我们需要解析注解的能容,让方法去认识和使用注解,方法如下:
import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class getzhujie { public static void main(String[] args) throws SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException { getxxx("COM.fanpeng.zhujie.ffs"); //字符串为使用注解的类的全类名 } public static Object getObject(String classfullname) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ return Class.forName(classfullname).newInstance(); //先让全类名反射,等到object类型 } // public static Method[] getmethod(String classfullname) throws SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException{ // return getObject(classfullname).getClass().getDeclaredMethods(); // } public static Method[] getmethod(Object obj) throws SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException{ return obj.getClass().getDeclaredMethods(); //然后得到这个类的所有方法的集合 } public static void getxxx(String classfullname) throws SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException{ Object object = getObject(classfullname); //先让全类名反射,等到object类型 Method[] methods = getmethod(object); //然后得到这个类的所有方法的集合 for (Method method : methods) { //遍历这个方法 Annotation[] annotations = method.getAnnotations(); //得到每个方法的注解集合 for (Annotation annotation : annotations) { //遍历注解 if (annotation instanceof qw) { //判断注解的名称是否与我们自己写的注解名称相同 qw lo=(qw) annotation; //如果相同,将注解强转成我们写的注解的类型 String str=lo.value(); //得到我们注解里面定义的value String hh=lo.hh(); //得到我们注解里面定义的hh method.invoke(object,new Object[]{str,hh}); //然后注入,让不同的注解去执行不同的方法 } } } }
这样我们的注解解析就做完了,现在我们用一个例子来看:
public class ffs { //这就是使用的类,上面那个字符串的全类名就是这个 @qw(value="login.action", hh="123") //我们可以给注解自定义值,这是注解里面的value和hh值就变成我们自定义的了 public void makeFefs(String str1, String str2){ System.out.println(str1+str2); } @qw //如果不自定义值,注解的值就是我们在最前边定义的那个值 public void makeFehfs(String str1, String str2){ System.out.println("str1+str2"); } @login //如果不自定义值,注解的值就是我们在最前边定义的那个值 public void makeFehfs(){ System.out.println("方法也可以不传值"); }
执行第二个类,我们就可以得到下面的结果:
login.action123 方法也可以不传值 str1+str2
上面的文章可以向我们展示,注解的值可以用到,也可以不用的,注解是方法的一部分
小白一个,错的地方请大家指出,第一次发博客,格式什么的也不懂
