Java instanceof与更改对象 [英] Java instanceof with changing objects

查看:117
本文介绍了Java instanceof与更改对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我该怎么办?

解决方案

如何做到这一点:

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

或者SomeClass是一个参数:

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

或者如果您希望实例为 someClass 而不是 someClass 的子类的实例:

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


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.

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

解决方案

How about this:

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

or if SomeClass is a parameter:

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

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

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

这篇关于Java instanceof与更改对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆