Skip to content

Commit

Permalink
Fix jdk proxy Object methods #7
Browse files Browse the repository at this point in the history
  • Loading branch information
liuzhengyang committed Jan 22, 2017
1 parent 9c0c350 commit 1e4f2f4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -272,10 +272,32 @@ private ChannelWrapper selectChannel() {
return channelWrappers.get(i);
}

private static Method hashCodeMethod;
private static Method equalsMethod;
private static Method toStringMethod;

static {
try {
hashCodeMethod = Object.class.getMethod("hashCode");
equalsMethod = Object.class.getMethod("equals", Object.class);
toStringMethod = Object.class.getMethod("toString");
} catch (NoSuchMethodException e) {
throw new NoSuchMethodError(e.getMessage());
}
}
public <T> T proxyInterface(final Class<T> serviceInterface) {
// Fix JDK proxy limitations and add other proxy implementation like cg-lib, spring proxy factory etc.
Object o = Proxy.newProxyInstance(RpcClientWithLB.class.getClassLoader(), new Class[]{serviceInterface}, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.equals(hashCodeMethod)) {
return proxyHashCode(proxy);
}
if (method.equals(equalsMethod)) {
return proxyEquals(proxy, args[0]);
}
if (method.equals(toStringMethod)) {
return proxyToString(proxy);
}
try {
return sendMessage(serviceInterface, method, args).getResponse();
} catch (Exception e) {
Expand All @@ -286,6 +308,18 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl
return (T) o;
}

private int proxyHashCode(Object proxy) {
return System.identityHashCode(proxy);
}

private boolean proxyEquals(Object proxy, Object other) {
return (proxy == other);
}

private String proxyToString(Object proxy) {
return proxy.getClass().getName() + '@' + Integer.toHexString(proxy.hashCode());
}

public void close() {
if (curatorFramework != null) {
curatorFramework.close();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.github.liuzhengyang.simplerpc.core;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

Expand Down Expand Up @@ -43,4 +44,14 @@ public void init() throws Exception {
}
}

@Test
public void testProxy() {
IHello hello = ClientBuilder.<IHello>builder().zkConn("127.0.0.1:2181")
.serviceName("testBuilder").serviceInterface(IHello.class).build();
System.out.println(hello.toString());
Assert.assertFalse(hello.equals(1));
Assert.assertTrue(hello.equals(hello));
System.out.println(hello.hashCode());
}

}

0 comments on commit 1e4f2f4

Please sign in to comment.