Ryan Leach
Ryan Leach

Reputation: 4470

When does var.getClass() return Object?

This commit: 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);

Adds a comparison and a log statement, when a passed in reference to a Block's class, is equal to Object.class

However, in my own testing

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);
    }
}

I get the following output:

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

When is .getClass able to return an Object.class?

I know it's possible, because we get many bug reports that contain that logging.

Upvotes: 0

Views: 72

Answers (1)

John Bollinger
John Bollinger

Reputation: 180201

Object.getClass() returns

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

(Object API docs)

That will be java.lang.Object.class if and only if the object's class is exactly java.lang.Object (not a subclass). This method is final, so you can rely on every object providing that implementation.

You may, however, also be interested in Class.isAssignableFrom() if you are looking for a way to determine reflectively whether one class is a superclass of another.

Upvotes: 2

Related Questions