1

Is there a way to use instanceof based on the passed argument of a method? Example

doSomething(myClass.class); /* I would like to call this also with other classes */

public void doSomething(/*generic parameter that accepts all classes, not just myClass */) {
  if (myObject instanceOf /* the generic parameter */ == true) {...}
}

sometimes I'll call the method using myClass.class but other times I would like to call it using someOtherClass.class - I don't want to change the if condition though. Is that possible? If so, how? :)

Thanks

2 Answers 2

7

You're looking for the Class.isInstance() method.

public void doSomething(Class<?> c, Object myObject) {
    if (c.isInstance(myObject)) {...}
}
Sign up to request clarification or add additional context in comments.

1 Comment

Although, technically speaking, this is changing the if condition. Still, +1, exactly what I would have suggested.
2

This is the way to do it, as far as I know:

public static <T> boolean doInstanceOf(Object object,Class<T> clz) {
        return clz.isInstance(object);
    }

Usage:

System.out.println(doInstanceOf(myObject,MyClass.class));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.