jeudi 20 juillet 2023

class.isInstance returns false but should report true

I have a library, which includes the following class:

@RequiredArgsConstructor
public class TypeConsumer<T> {

    private final Class<T> clazz;
    private final Consumer<T> consumer;

    public void consume(Object object) {
        if (clazz.isInstance(object)) {
            this.consumer.accept((T) object);
        }
    }
}

In a other project I have a Class. Lets call it A and an other class B. B extends A. In this other project I use to following code

B b = new B();
TypeConsumer<A> consumer = new TypeConsumer<>(A.class, System.out::println)
consumer.consume(b);

Every time. the check is false, but I don't know why. I tested clazz.isAssignableFrom(b.getClass()) too, but the check is always false, but it should be true, because as I said, B extends A

What do I have to change or what did I wrong, to let the check work correctly





Aucun commentaire:

Enregistrer un commentaire