当前位置: 代码迷 >> Web前端 >> JAVA 署理方式实现接口实例化,WebService的方式实现远程方法调用
  详细解决方案

JAVA 署理方式实现接口实例化,WebService的方式实现远程方法调用

热度:142   发布时间:2012-07-05 07:59:18.0
JAVA 代理方式实现接口实例化,WebService的方式实现远程方法调用
接口工厂
/**
 * <pre>
 * Title: 接口工厂
 * </pre>
 */
public abstract class AbstractInterfaceFactory {
    protected static final Logger logger = Logger
            .getLogger(AbstractInterfaceFactory.class.getName());
    
    public static AbstractInterfaceFactory getInstance(){
        return new DefaultInterfaceFactory();
    }
    
    
    /** 私有化, */
    protected AbstractInterfaceFactory(){}
    
    
    public <T> T getWebService(Class<T> oldInterface) {
        InterfaceHandler intr = new InterfaceHandler(this);

        Object bufferedInter = Proxy.newProxyInstance(getClass()
                .getClassLoader(), new Class[] { oldInterface }, intr);

        return (T) bufferedInter;
    }

    /** 子类实现 */
    protected abstract  Object remoteCall(String methodName, Object[] args);

    /** 代理类 */
    private static final class InterfaceHandler implements InvocationHandler {
        private AbstractInterfaceFactory factory;

        public InterfaceHandler(AbstractInterfaceFactory factory) {
            this.factory = factory;
        }

        
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String remoteMethodName = method.getName();
            logger.info("开始调用接口:" + remoteMethodName);

            Object rst = factory.remoteCall(remoteMethodName, args);

            logger.info("完成调用");
            return rst;
        }

    }
 
    /** 静态工厂的默认实现 */
    private static final class DefaultInterfaceFactory extends AbstractInterfaceFactory {
        protected Object remoteCall(String methodName, Object[] args) {
            logger.info("远程方法调用中.....");
            return methodName;
        }
    }
}


实际接口
/**
 * 
 * <pre>
 * Title: 任意定义的两个接口
 * </pre>
 */
public interface MyInterface {
    public String getVersion();
    
    public String doJob();
}


测试类
public class testInterfaceFactory {
    public static void main(String[] args) {
        AbstractInterfaceFactory factory = AbstractInterfaceFactory.getInstance();
        MyInterface intr = factory.getWebService(MyInterface.class);
        System.out.println("获取版本:" + intr.getVersion());
        
        intr = factory.getWebService(MyInterface.class);
        System.out.println("doJob:" + intr.doJob());
    }
}


运用:远程调用WebService时,可以考虑使用。
  相关解决方案