gpt4 book ai didi

java - var.getClass() 什么时候返回 Object?

转载 作者:行者123 更新时间:2023-12-02 02:22:45 24 4
gpt4 key购买 nike

此提交:https://github.com/SpongePowered/SpongeCommon/commit/704ef84398255d66da104e2b43dec7f2c2aa40c3#diff-0570d221b4c69a232692ff6be6369ea3R79

   public static String getIdAndTryRegistration(IProperty<?> property, Block block, String blockId) {
<snip>
+ Class<?> blockClass = block.getClass();
+ while (true) {
+ if (blockClass == Object.class) {
+ final String originalClass = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, block.getClass().getSimpleName());
+ final String propertyId = originalClass + "_" + property.getName();
+ LogManager.getLogger("Sponge").warn("Could not find {} owning class, assigning fallback id: {}", property.getName(),
+ propertyId);

当传入的 Block 类的引用等于 Object.class 时,添加比较和日志语句

但是,在我自己的测试中

package org.spongepowered.test;

public class test {


public static class Parent{}
public static class Child extends Parent {}

public static void main(String[] args) {
Class<?> child = Child.class;
Class<?> parent = Parent.class;
System.out.println(child +"::"+parent);
boolean b = Object.class == child;
boolean c = Object.class == parent;
System.out.println( b+"::"+c);

System.out.println("==============================================");

Class<? extends Child> child2 = Child.class;
Class<? extends Parent> parent2 = Parent.class;
System.out.println(child2 +"::"+parent2);
//boolean b2 = Object.class == child2;
//boolean c2 = Object.class == parent2;
//System.out.println( b2+"::"+c2);
}
}

我得到以下输出:

class org.spongepowered.test.test$Child::class org.spongepowered.test.test$Parent
false::false
==============================================
class org.spongepowered.test.test$Child::class org.spongepowered.test.test$Parent

Process finished with exit code 0

.getClass什么时候能够返回Object.class?

知道这是可能的,因为我们收到许多包含该日志记录的错误报告。

最佳答案

Object.getClass() 返回

The Class object that represents the runtime class of this object.

( Object API docs )

当且仅当对象的类恰好是java.lang.Object(不是子类)时,这才是java.lang.Object.class。此方法是final,因此您可以依赖提供该实现的每个对象。

但是,如果您正在寻找一种方法来反射(reflection)性地确定一个类是否是另一个类的父类(super class),您可能也会对 Class.isAssignableFrom() 感兴趣。

关于java - var.getClass() 什么时候返回 Object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48273634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com