具有变化对象的 Java instanceof

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12766233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:07:39  来源:igfitidea点击:

Java instanceof with changing objects

javadynamicinstanceof

提问by Nicolas Martel

I need a method where i could pass on a parameter which i assume would be a Class (not sure though) and in that method, instanceof would be used to check if x is an instance of the passed Class.

我需要一个方法,我可以在其中传递一个参数,我认为该参数是一个类(虽然不确定),并且在该方法中,instanceof 将用于检查 x 是否是传递的类的实例。

How should i do that? I tried a few things but none worked.

我该怎么做?我尝试了几件事,但没有奏效。

回答by Stephen C

How about this:

这个怎么样:

public boolean checker(Object obj) {
    return obj instanceof SomeClass;
}

or if SomeClass is a parameter:

或者如果 SomeClass 是一个参数:

public boolean checker(Object obj, Class someClass) {
    return someClass.isInstance(obj);
}

or if you want the instance to be someClassand NOT an instance of a subclass of someClass:

或者,如果您希望该实例成为someClass而不是以下子类的实例someClass

public boolean checker(Object obj, Class someClass) {
    return someClass.equals(obj.getClass());
}