Passing a class as an argument to a method in java

tor picture tor · Feb 13, 2013 · Viewed 35.7k times · Source

I am writing a method were I would like to pass a class to a method, where a part of the code includes checking if the object is of a certain type. This is what I want (but which obviously doesn't work):

private static class MyClass1 { /***/ }
private static class MyClass2 { /***/ }

private void someFunc() {
    /* some code */
    methodName(MyClass1);
    methodName(MyClass2);
}


private void methodName(Class myClass) {
    Object obj;
    /* Complicated code to find obj in datastructure */
    if (obj instanceof myClass) {
        /* Do stuff */
    }
}

Any hints as to how this can be done? Thanks!

Answer

Ryan Stewart picture Ryan Stewart · Feb 13, 2013

Class has both an isInstance() method and an isAssignableFrom() method for checking stuff like that. The closest to what you're looking for is:

if (myClass.isInstance(obj)) {

Update: From your comment, you want to pass the name of a class into a method and check if something is assignable to that class. The only way to do that is to pass the class name as a String, then load the class and use one of the aforementioned methods. For instance (exception handling omitted):

private void methodName(String className) {
    Class myClass = Class.forName(className);
    Object obj;
    /* Complicated code to find obj in datastructure */
    if (myClass.isInstance(obj)) {
        /* Do stuff */
    }
}