Passing a class as an argument to a method in java

狂风中的少年 提交于 2019-11-29 13:21:45

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 */
    }
}

I think you want to know object's class type at runtime.. so use reflaction api for that. and for your problem this solution i think work

public class Clazz {
public static void main(String[] args) {
    Clazz clazz = new Clazz();
    ArrayList list = new ArrayList<>();
    Class myClass = list.getClass();
    clazz.display(myClass);
}

/**
 * Modified By nirav.modi on Feb 13, 2013
 */
private void display(Class myClass) {
    ArrayList list = new ArrayList<>();
    if(myClass.isInstance(list)) {
        System.out.println("Yooo , its instance..");
    }else {
        System.out.println("Not instance");
    }
}

}

MyClass1 myClass1 = new MyClass1();
if(MyClass1.class.isInstance(myClass1))
    System.out.println("(MyClass1.class.isInstance(myClass1) is TRUE");
else
    System.out.println("(MyClass1.class.isInstance(myClass1) is FALSE");

Object myClass2 = new MyClass2();
Class class1 = myClass1.getClass(); 
Class class2 = myClass2.getClass();
System.out.println("class1 == class2 : " + ( class1 == class2));
System.out.println("class1.isAssignableFrom(class2) = " 
    + class1.isAssignableFrom(class2));

MyClass1 myClass3 = new MyClass1();
Class class3 = myClass3.getClass();
System.out.println("class1 == class3 : " + ( class1 == class3));
System.out.println("class1.isAssignableFrom(class3) = " 
    + class1.isAssignableFrom(class3));

OUPUT:

(MyClass1.class.isInstance(myClass1) is TRUE
class1 == class2 : false
class1.isAssignableFrom(class2) = false
class1 == class3 : true
class1.isAssignableFrom(class3) = true
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!