java 动态实现接口

package com.yhouse.modules.daos;

public interface IUserDao {
    public String getUserName();
    public String Say();
}

2.

package com.yhouse.modules.daos;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MethodProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)  throws Throwable {        
        //如果传进来是一个已实现的具体类(本次演示略过此逻辑)
        if (Object.class.equals(method.getDeclaringClass())) {  
            try {  
                return method.invoke(this, args);  
            } catch (Throwable t) {  
                t.printStackTrace();  
            }  
        //如果传进来的是一个接口(核心)
        } else {  
            System.out.println(method.getName());
            return run(method, args);  
        }  
        return null;
    }
    
    /**
     * 实现接口的核心方法 
     * @param method
     * @param args
     * @return
     */
    public Object run(Method method,Object[] args){  
        //TODO         
        //如远程http调用
        //如远程方法调用(rmi)
        //....
    
       return "method call success!";
    }  
}

3.

package com.yhouse.modules.daos;

import java.lang.reflect.Proxy;

public class Test {

    public static void main(String[] args) throws ClassNotFoundException {
        // TODO Auto-generated method stub
    
         String className = "com.yhouse.modules.daos.IUserDao";
          String methodName = "Say";
          Class clz = Class.forName(className);
          
        
          // Object newProxyInstance = Proxy.newProxyInstance(IUserDao.class.getClassLoader(),  new Class[]{IUserDao.class},m);
        MethodProxy m=new MethodProxy();
         Object newProxyInstance = Proxy.newProxyInstance(clz.getClassLoader(),  new Class[]{clz},m);
         
         IUserDao ud=((IUserDao)newProxyInstance);
        String s= ud.getUserName();
         System.out.println(s);
         
      String s1=ud.Say();
         System.out.println(s1);

    }

}

 

posted @ 2018-01-14 16:42  甜菜波波  阅读(810)  评论(0编辑  收藏  举报