0

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; } 

as described previously

1
  • is cls_Super really defined as a class? in the scope you provided it is a variable name. Commented May 29, 2023 at 11:43

1 Answer 1

2

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.