Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a class as an argument to a method in java

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!

like image 830
tor Avatar asked Feb 13 '13 05:02

tor


1 Answers

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 */
    }
}
like image 170
Ryan Stewart Avatar answered Oct 25 '22 21:10

Ryan Stewart