anon
anon

Reputation:

How should this instanceof condition look like?

I have a list of nodes. This nodes are a data class I defined by myself. Each node has a data field of the type Object. Now I want to find the node in a list of nodes that has the parameter object in the data field. I wrote this method, because I wanted to first compare if the two objects (the parameter and the object in the data field) are of the same type:

public Node getnNodeByData(Object obj) {
    for (Node node : nodes) {
        if (node.getData() instanceof obj.getClass()) {

        }
    }
}

Unfortunately this condition does not work:

Incompatible operand types boolean and Class<capture#1-of ? extends Graph>

I don't really know why this is a problem. How can I make this working?

Upvotes: 0

Views: 796

Answers (2)

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

No, that is not possible like that. You should use isAssignableFrom() or isInstance(). The difference between the two methods is that isInstance(null) will return false and isAssignableFrom(null) will give true.


[object] instanceof [class]

should be translated to this:

[class].class.isAssignableFrom(object.getClass());

Example:

Integer i = 4;
boolean b = i instanceof Number;
boolean k = Number.class.isAssignableFrom(i.getClass());

b and k are equivalent.

Upvotes: 3

Louis Wasserman
Louis Wasserman

Reputation: 198073

No, you need to use Class.isInstance(Object). The instanceof keyword does not expect an object of type Class, but only the name of the class directly -- but Class.isInstance is basically analogous.

Upvotes: 4

Related Questions