7

类实例对象的class类型却不属于该类,何解?

 2 years ago
source link: https://segmentfault.com/a/1190000040799771
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

类实例对象的class类型却不属于该类,何解?

标题可能会让人一头雾水,直接上例子

如果我们在代码中,执行如下内容

server instanceof MvpServer

它返回的东西会是啥,如果得出正确答案的朋友,下面内容就可以不用看了。

当时看到这个答案,我真的一脸懵逼,还一度怀疑是我idea问题

像这种问题,有时候真的得靠平时的积累了,类是由什么进行加载?答案是类加载器,即使类包名一样,类名字一样,如果你是由不同的类加载器进行加载,则该类也是不一样。因此我们就可以优先从类加载器排查起

从图片就很容易看出来,server和MvpServer的类加载器不一样。server他这个类加载器是spring devtools这个包提供的。因此解决的思路就很简单,就查下项目中是否引入

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

有的话,可以直接去掉了,避免对项目产生影响。如果你确实不想去掉,你可以把当前整个线程的类加载器,都设置成spring-boot-devtools的类加载器,可以通过

  Thread.currentThread().setContextClassLoader();

当我们把类加载都改成一样后,我们再来看下效果

可能我们平时会背一些八股文,类加载器比如boostrap classloader、ext classloader、app classloader啥的,但有时候真的排查起问题,就会忽略了


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK