Search code examples
javahashmapimmutabilityhashcodejava.lang.class

Is Class<T> immutable in Java, also known as, is Class<T> a safe key for HashMap?


I have been lurking the net for a while now, but haven't found an answer to this yet. Someone is mentioning Class<T> as key here on SO (I think) but I can't find the post anymore. In any case, this question deserves a proper answer (apologizing if there is a thousand post thread on it).

Is Class<T> immutable? Can it be safely and efficiently used as key (constant hashCode() over execution) ?

My guess would be yes, because the Class definition doesn't change at runtime. But I am not quite sure...thank you!

EDIT: talking about Java.


Solution

  • An immutable object in Java is one that cannot have its internal state changed via any normal (non-reflective) execution paths. This means that:

    • The class defines no accessible methods that mutates its internal state
    • The class is designed in such a way as to prevent sub-classes from mutating its internal state

    The Java Class class fulfills these requirements:

    • It provides no methods for mutating its internal state.
    • The class itself is final, and cannot be sub-classed.

    The actual class definition of course, is loaded by the JVM via a classloader, and once defined, is set for the lifetime of that JVM and does not change.