天天看点

模拟注解编程(Java注解实战——使用注解对对象赋值)需要的基础知识——注解和反射思路正文

模拟注解编程(Java注解实战——使用注解对对象赋值)

  • 需要的基础知识——注解和反射
  • 思路
  • 正文

我在学习spring的过程中思考过一个问题,为什么仅仅标记一些注解,spring就可以帮我们管理对象间的依赖关系呢?本文举一个例子,希望可以给各位带来一点启发

需要的基础知识——注解和反射

注解也是Java中非常重要的一部分内容,在以往的学习中往往被人忽视,在这里就不多论述了,如果想要了解更多的同学,可以参考下面这篇文章,文章内容通俗易懂

链接: java注解-最通俗易懂的讲解.

反射在动态代理的过程中有着举足轻重的地位,所以可以先复习以下再看下去。

思路

首先通过自定义的注解,设置元信息,再利用动态代理,将元信息的值,赋值给代理对象。

正文

自定义的注解 ProxyAnnotation

//运行时有效
@Retention(RetentionPolicy.RUNTIME)
public @interface ProxyAnnotation {
    //将内容赋值
    String name() default "";
    boolean isProxy() default false;
}
           

动态代理所需要实现的接口

public interface Beans {
    void saySomething();
}
           

标注注解的类 Bean

@ProxyAnnotation(isProxy = true,name = "JMing.club")
public class Bean implements Beans{
    private String name;

    public void saySomething(){
        System.out.println("this is my bean ... "+this.name);
    }
}
           

返回代理对象的工厂模式 BeanFactory

public class BeanFactory {

    public static Object getBean(){
        return Proxy.newProxyInstance(Bean.class.getClassLoader(), Bean.class.getInterfaces(), new InvocationHandler() {
            Bean bean = new Bean();
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            //判断对象是否标注了ProxyAnnotation注解
                if(bean.getClass().isAnnotationPresent(ProxyAnnotation.class)){
                //返回注解
                    ProxyAnnotation proxyAnnotation = bean.getClass().getAnnotation(ProxyAnnotation.class);
                    //获取注解信息
                    boolean isProxy = proxyAnnotation.isProxy();
                    String name = proxyAnnotation.name();
                    //获取需要赋值的域对象
                    Field nameField = bean.getClass().getDeclaredField("name");
                    //因为是私有域,需要修改访问权限
                    nameField.setAccessible(true);
                    //修改属性的值
                    nameField.set(bean, name);
                }
                //返回执行方法的对象
                Object o1 = method.invoke(bean, objects);
                return o1;
            }
        });
    }
}
           

测试类

public class AnnotationTest {
    public static void main(String[] args) {
        Beans bean = (Beans) BeanFactory.getBean();
        bean.saySomething();
    }
}

           

测试结果

this is my bean ... JMing.club

Process finished with exit code 0
           

可以看到,最后实现了通过注解对对象的属性进行赋值。