Kousha
Kousha

Reputation: 36189

Java pass a class to check instance of

I want to pass a class to a function. In that function, new instance of other classes are created.

Then, I want to be able to find which object there is an instance of the class I passed:

public void doSomething(Class cls) {
    SomeObject obj = new SomeObject();

    if (obj instanceof cls) {
        // Do amazing things here
    }
}

class Person {
    // This exists
}

doSomething(Person.class);

The code above doesn't work. I hope I'm clear enough what I'm trying to do.

Upvotes: 0

Views: 528

Answers (2)

Sweeper
Sweeper

Reputation: 271050

If you want to see if an object is an instance of a class type, you need to call isInstance:

if (cls.isInstance(obj)){

}

Or you can do isAssignableFrom:

if (clas.isAssignableFrom(obj.getClass())) {

}

Upvotes: 1

Christian Ullenboom
Christian Ullenboom

Reputation: 1458

You want to use https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isInstance-java.lang.Object-.

if (cls.isInstance(obj)){
 ...
}

Upvotes: 7

Related Questions