[英]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.
我希望我已经很清楚我要做什么。
You want to use https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isInstance-java.lang.Object- . 您要使用https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isInstance-java.lang.Object- 。
if (cls.isInstance(obj)){
...
}
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.