Problem with overriding hashCode for POJO Active Object
Reported by user (Eirik <eirirlar@gmail.com>):
I've discovered that overriding equals and hashcode should be done with care. This might be obvious, but consider the following class: public class Terminal { private String id; public Terminal() { this.id = "xz"; } public Terminal(String id) { this.id = id; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Terminal other = (Terminal) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } } The equals method is the default eclipse implementation which also compares the class (instead of doing instanceof). Running a simple test: public class ActiveObjectTest { @Test public void testActiveObjectCreation() { ActiveObject.newInstance(Terminal.class, 1000); } } Causes the following exception: java.lang.NullPointerException at acterminals.Terminal$$ProxiedByAWSubclassing$$1266339987685.aw $getAroundAdvice(Unknown Source) at acterminals.Terminal$$ProxiedByAWSubclassing$ $1266339987685_1_1984935277_147697296___AW_JoinPoint.invoke(Unknown Source) at acterminals.Terminal$$ProxiedByAWSubclassing$ $1266339987685.hashCode(Unknown Source) at java.util.WeakHashMap.getEntry(WeakHashMap.java:378) at java.util.WeakHashMap.containsKey(WeakHashMap.java:369) at org.codehaus.aspectwerkz.aspect.DefaultMixinFactory.mixinOf (DefaultMixinFactory.java:122) at org.codehaus.aspectwerkz.aspect.management.Mixins.mixinOf (Mixins.java:147) at org.codehaus.aspectwerkz.aspect.management.Mixins.mixinOf (Mixins.java:129) at acterminals.Terminal$$ProxiedByAWSubclassing$$1266339987685.<init> (Unknown Source) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance (NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance (DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:308) at org.codehaus.aspectwerkz.proxy.ProxySubclassingStrategy.newInstance (ProxySubclassingStrategy.java:88) at org.codehaus.aspectwerkz.proxy.Proxy.newInstance(Proxy.java:86) at se.scalablesolutions.akka.actor.ActiveObject$.newInstance (ActiveObject.scala:186) at se.scalablesolutions.akka.actor.ActiveObject$.newInstance (ActiveObject.scala:42) at se.scalablesolutions.akka.actor.ActiveObject.newInstance (ActiveObject.scala) at acterminals.ActiveObjectTest.testActiveObjectCreation (ActiveObjectTest.java:11) Should hashcode and equals be implemented Scala-style instead?
Leave a comment
No more pure POJO Typed Actor