Why Unsafe.allocateInstance(Class.class) failed?

瘦欲@ 提交于 2019-12-12 04:06:52

问题


I'm now using unsafe. When I run the following code:

unsafe.allocateInstance(Class.class)

There happen's

Exception in thread "main" java.lang.IllegalAccessException: java.lang.Class

Since Class is a non-abstract class, why it so special? And is there any way to construct an 'empty' Class like allocateInstance?


回答1:


Because there is an explicit check inside HotSpot JVM to ensure that java.lang.Class cannot be instantiated through JNI, Unsafe etc. See instanceKlass.cpp:

void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
  if (is_interface() || is_abstract()) {
    ResourceMark rm(THREAD);
    THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
              : vmSymbols::java_lang_InstantiationException(), external_name());
  }
  if (this == SystemDictionary::Class_klass()) {
    ResourceMark rm(THREAD);
    THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
              : vmSymbols::java_lang_IllegalAccessException(), external_name());
  }
}

Such instance would not be valid anyway, so it does not make sense.



来源:https://stackoverflow.com/questions/45751715/why-unsafe-allocateinstanceclass-class-failed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!