2

Let's say I have some class

public class SomeClass<T> {
    public SomeClass() {
        //or throw exception here if T is not an interface but this is not preferred.
    }
}

Can I somehow require T to have equals and hashCode overriden Object's implementations? One way I can think of is using something like this:

public class SomeClass<T extends SomeClass.GoodClass> {
    public static abstract class GoodClass {
        protected abstract boolean equalsImpl(Object other);

        @Override
        public final boolean equals(Object other){
            return equalsImpl( other );
        }
    } 
}

But I do want to use the abstract class approach since I cannot use any classes which extend some other class (no multiple inheritence, and using a wrapper just adds even more boiler plate).

For the exception route maybe I can use something from How to check if a class has overridden equals and hashCode and https://stackoverflow.com/a/13974262/5130921.

Community
  • 1
  • 1
Aarjav
  • 1,334
  • 11
  • 22
  • There is no way to require a generic type that overrides Object's `hashCode` and `equals()`. After type erasure, generics are `java.lang.Object` anyway. – Elliott Frisch Jan 20 '16 at 01:04

0 Answers0