首先,定义一个接口如下:
interface Protocol{ public String getName(String a, int b); } 两个实现类: class Impl01 implements Protocol{ @Override public String getName(String a, int b) { return "I'm 01"; } } class Impl02 implements Protocol{ @Override public String getName(String a, int b) { return "I'm 02"; } }
测试类:
class Test{ public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<?> clazz = Protocol.class; Method method = clazz.getMethod("getName", String.class, int.class); method.invoke(new Impl01(), "01--", 11); method.invoke(new Impl02(), "02--", 22); } }
结果:
01--11
02--22
在hadoop rpc中,客户端通过动态代理取得调用方法的上下文信息后,会将这些信息发送给服务端,服务端就是利用这些信息,取得要调用的接口的方法,然后调用服务端实例的方法,具体细节后面后一一展开。