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);

    }

}

 

转载于:https://www.cnblogs.com/tiancai/p/8283640.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值