jeudi 27 décembre 2018

How should Type type hierarchy types be implemented?

When generics were added to 1.5, java.lang.reflect added a Type interface with various subtypes to represent types. Class is retrofitted to implement Type for the pre-1.5 types. Type subtypes are available for the new types of generic type from 1.5.

This is all well and good. A bit awkward as Type has to be downcast to do anything useful, but doable with trial, error, fiddling and (automatic) testing. Except when it comes to implementation...

How should equals and hashCode be implemented. The API description for the ParameterizedType subtype of Type says:

Instances of classes that implement this interface must implement an equals() method that equates any two instances that share the same generic type declaration and have equal type parameters.

(I guess that means getActualTypeArguments and getRawType but not getOwnerType??)

We know from the general contract of java.lang.Object that hashCode must also be implemented, but there appears to be no specification as what values this method should produce.

None of the other subtype of Type appear to mention equals or hashCode, other than that Class has distinct instances per value.

So what do I put in my equals and hashCode?

(In case you are wondering, I am attempting to substitute type parameters for actual types. So if I know at runtime TypeVariable<?> T is Class<?> String then I want to replace Types, so List<T> becomes List<String>, T[] becomes String[], List<T>[] (can happen!) becomes List<String>[], etc.)

Or do I have to create my own parallel type type hierarchy (without duplicating Type for presumed legal reasons)? (Is there a library?)





Aucun commentaire:

Enregistrer un commentaire