简体   繁体   中英

How to extend package-private class in `java.util`

I would like to extends Collections.UnmodifiableRandomAccessList with a custom hashCode/equals implementation, but without the mess of delegation or copying and pasting the implementation. In trusted code, I thought it would be easy. However, my attempt to declare my new class in package java.util gave me a SecurityException . Is there any way around it?

If you were able to override it, it would give you the opportunity to allow editing the state, which contradicts the purpose of the class (immutability). Java chose to include this as package-private, but in other instances (like String ) these precautions are implemented using final instead, also to prevent subclassing.

[addendum] Both hashCode/equals delegate to the list being wrapped, so subclassing the list being wrapped will also change the behavior of the UnmodifiableRandomAccessList .

HotSpot uses at least three ClassLoaders that are responsible for loading classes into the JVM. The system ClassLoader (the one that loads user code) refuses to load classes into certain namespaces like java and java.util (but not, eg, java.nio ). AFAIK, there is no way to convince it otherwise. The solution is to ask the bootstrap ClassLoader (the one that loads Java's base classes) to do it, via the -Xbootclasspath/a JVM switch as documented here .

Btw, for conveniently implementing a List that delegates to another implementation, see Guava's ForwardingList .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM