Java: instanceof无法编译

huangapple go评论67阅读模式
英文:

Java: instanceof doesn't compile

问题

I'm a newbie to Java and want to write a method checking if this object is of a sub class of given class <p_SuperClassName>.
Eclipse denies compilation of the following code giving the message that "cls_Super can not be resolved to a type". I don't know why. Do you have a quick answer to this? Thx a lot in advance!

protected boolean isOfSubClassOf(String p_SuperClassName) {
    boolean res = false;

    Class<?> cls_Super = null;
    try {
        cls_Super = Class.forName(p_SuperClassName);
        res = (this instanceof cls_Super);
    } catch (ClassNotFoundException cnfe) {
        System.out.println("ClassNotFoundException: Did not find class '" + p_SuperClassName + "'.");
        cnfe.printStackTrace();
    }
    return res;
}

如前所述。

英文:

I'm a newbie to Java and want to write a method checking if this object is of a sub class of given class <p_SuperClassName>.
Eclipse denies compilation of the following code giving the message that "cls_Super can not be resolved to a type". I don't know why. Do you have a quick answer to this? Thx a lot in advance!

protected boolean isOfSubClassOf(String p_SuperClassName) {
    boolean res = false;

    Class&lt;?&gt; cls_Super = null;
    try {
        cls_Super = Class.forName(p_SuperClassName);
        res = (this instanceof cls_Super);
    } catch (ClassNotFoundException cnfe) {
        System.out.println(&quot;ClassNotFoundException: Did not find class &#39;&quot; + p_SuperClassName + &quot;&#39;.&quot;);
        cnfe.printStackTrace();
    }
    return res;
}

as described previously

答案1

得分: 2

无法使用instanceof关键字来检查类变量,只能使用文字类型名称(例如obj instanceof ActualSuperClassName)。使用类型为Class的实例(例如您的示例中的cls_Super),可以通过使用Class.isInstance方法执行相同的测试,如下所示:

res = cls_Super.isInstance(this);
英文:

You can't use a Class variable with the instanceof keyword, only the literal type name (e.g. obj instanceof ActualSuperClassName). With an instance of type Class (i.e. cls_Super, in your example), you can perform the same test by using the Class.isInstance method, i.e.:

res = cls_Super.isInstance(this);

huangapple
  • 本文由 发表于 2023年5月29日 19:42:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76357051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定