自動實現接口的實例,mybatis就是這樣實現的


思考

很多人用過MyBatis,或者使用過SpringData,那么和傳統的jdbc相比,差別在哪里呢?傳統的dao層,接口需要有實現,需要連接發出sql,需要接收返回值,但是mybatis只需要實現接口,而不需要實現類,而且神奇的是,可以通過spring的注解,直接把接口的實現對象給取出,大家都知道,接口是不可實例化的,也就是不能創建對象,但是我們只聲明了接口,那么這個實例是怎么來的呢?

 

 

一:原理

使用了動態代理,真正的對象,是一個代理對象

 

二:代碼

 

 InvocationHandler handler = new InvocationHandler() {

            /**
             * 代理對象 執行方法 方法參數
             */
            @Override
            public Object invoke(Object handler, Method method, Object[] params) throws Throwable {
                Dao dao = method.getAnnotation(Dao.class);
                if (null != dao) {
                    String value = dao.value();
                    System.out.println(value);
                    
                } else {
                    System.out.println("null");
                }

                Class<?> returnType = method.getReturnType();
                System.out.println(returnType.getName());
                return null;
            }
        };

        @SuppressWarnings("unchecked")
     Class
<Animal> cl = (Class<Animal>) Class.forName("zxj.proxy.Animal"); Class<?>[] cc = { cl }; Object instance = Proxy.newProxyInstance(Animal.class.getClassLoader(), cc, handler); System.out.println(instance.getClass().getName()); Animal an = (Animal) instance; an.run(); an.call(); an.eat();

 

 

下面給出接口的代碼:

package zxj.proxy;

public interface Animal {

    @Dao("走")
    public void run();

    @Dao("吃")
    public void eat();

    @Dao("叫")
    public String call();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM