zoukankan      html  css  js  c++  java
  • 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);
    
        }
    
    }
  • 相关阅读:
    signals系列之一——基本用法
    libevent系列之一——libevent介绍
    memcached完全剖析系列——一、memcached基础
    分布式算法一——一致性hash算法
    spring容器启动过程
    dubbo源码之四——服务发布二
    dubbo源码之四——dubbo服务发布
    dubbo源码之三——dubbo重构
    dubbo源码之三-模块依赖
    [模板](luogu P3387)縮點
  • 原文地址:https://www.cnblogs.com/tiancai/p/8283640.html
Copyright © 2011-2022 走看看