繁体   English   中英

Serializable.class 如何不能从 Class.class 分配?

[英]How can Serializable.class not be assignable from Class.class?

org.springframework.core.SerializableTypeWrapper (版本 5.2.3)中,第 112 行有以下代码:

    if (GraalDetector.inImageCode() || !Serializable.class.isAssignableFrom(Class.class)) {
        // Let's skip any wrapping attempts if types are generally not serializable in
        // the current runtime environment (even java.lang.Class itself, e.g. on Graal)
        return providedType;
    }

I'm curious about the second check ( .Serializable.class.isAssignableFrom(Class.class) ): is it possible for it to evaluate to true (that is, for Serialazable.class to be not assignable from Class.class )?

这是Class#isAssignableFrom() javadoc 所说的:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

查看Class的代码,我看到以下内容:

public final class Class<T> implements java.io.Serializable

所以SerializableClass的超接口,应该总是可以从Class分配。 但是 Spring 代码中的检查表明有时不是。

怎么来的? 在什么情况下会发生这种情况,为什么它们不违反 Java 语言规范?

自定义class 加载器是表达式返回false的一种可能(如果不太可能)机制。 自定义 class 加载器可以做一些疯狂的事情,包括加载他们自己版本的标准 Java 类。 关于 class 装载机的一些知识:

  • 自定义 class 加载器可以配置为加载任何 class,甚至包括 Java 标准库类(当然不鼓励,但仍然可能)
  • 自定义 class 加载器通常配置为将其不知道如何加载的类委托给系统 class 加载器。
  • 当 class A 具有对 class B 的引用时,将使用用于加载 class 加载器的任何 class 加载器来解析引用
  • More than one class loader can be configured to handle the same class, which can lead to multiple versions of a class getting loaded into the JVM, with the actual implementation you get depending on which class loader you ask

Suppose there is a custom class loader that, for whatever reason, is configured to load java.io.Serializable by itself, but delegates to the system class loader for loading other classes, including java.lang.Class .

现在假设这个自定义 class 加载器用于加载SerializableTypeWrapper 这意味着它还将用于解析对SerializableTypeWrapperjava.io.Serializable的引用。 参考java.lang.Class ,自定义 class 加载程序会将其委托给系统 ZA2F2ED4F8EBC2CBBDZC2A1。 The system class loader will be used to load java.lang.Class , but it will also be used to load the reference to java.io.Serializable from within java.lang.Class .

So now we can ask the question - is java.io.Serializable [custom] assignable from java.lang.Class [standard] ? And the answer is no - java.lang.Class does implement java.io.Serializable [standard] , but it does not implement java.io.Serializable [custom] .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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