简体   繁体   English

Java传递一个类来检查实例

[英]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. 我希望我已经很清楚我要做什么。

If you want to see if an object is an instance of a class type, you need to call isInstance : 如果要查看对象是否是类类型的实例,则需要调用isInstance

if (cls.isInstance(obj)){

}

Or you can do isAssignableFrom : 或者您可以执行isAssignableFrom

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何传递类名作为参数,然后使用它来检查对象是否是Java中该类的实例? - How to pass class name as parameter and then using it to check if an object is an instance of that class in java? 如何检查一个类在Java中是否有任何实例? - How to check if a class has any instance in Java? 如何检查一个类的特定实例是否在java中运行? - how to check if a specific instance of a class is running in java? 在Java中将类作为参数进行扩展检查 - Pass class as parameter with extension check in Java 用Java检查类的天气对象是否分配了类实例的方法是什么? - What is way to check weather object of class is assigned an instance of class or not in Java? Java-如何在类定义中检查对象是否是类的实例 - Java - How to check if an object is an instance of a class in the class definition Java-将实例从一个类传递到另一个类 - Java- Pass instance from one class to another 将Java对象的实例类型传递给通用类类型参数 - Java Pass instance type of Object to generic class type parameter 将类的实例传递给其他类的适当方法(Java) - Appropriate way to pass instance of class to other classes (Java) 如何将实例传递给必须实现接口的类,然后在Java中使用它? - how to pass a instance to a class that must implement an interface and then use it in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM