Java debuggers see this field, because they rely on JDWP, which works on top of native APIs: JNI and JVM TI.
You technically can access/modify classLoader
field with JNI
or Unsafe, but please don't do this!
After all, why do you think this field is filtered from reflection access? Exactly to prevent people from shooting themselves in the foot by modifying the field.
The key point is that a class should never be separated from its class loader. HotSpot JVM cannot unload classes one by one; instead, it unloads the whole class loader, when no live references to the ClassLoader
object remain.
When a ClassLoader
object is garbage collected, the corresponding part of the Metaspace can be reclaimed, along with the metadata for all classes loaded by this ClassLoader
.
Now, what happens if you null out classLoader
field? If there are no more references to the corresponding ClassLoader
, it becomes eligible for garbage collection (seems like exactly what you want). But this may trigger class unloading, that will kill all the metadata for classes of this loader. However, classes (and their instances) are completely broken without the metadata. After that, any operation on your class or one of its instances may randomly crash JVM or make the application otherwise unstable.