Search code examples
javanashorn

Java nashorn compare if a java objects is of a certain java type


I am using instanceof but it is currently not working as I expect it. I have a variable I retrieve from my java code inside my script. Let's call this variable myObject which is the instance of a MyObject class, as you would expect.

if (myObject instanceof Java.type("MyObject")) {
    //The check doesn't pass; the code here doesn't execute
}

I could only find vague information on the net about this. What is the definite way of checking if myObject is an instance of the MyObject class as I would easily do in Java?

Thanks!


Solution

  • What you have should work, (with fully qualified class names, of course). E.g. this definitely works:

    jjs> var x = new java.util.BitSet()
    jjs> x instanceof Java.type("java.util.BitSet") 
    true
    

    Note: java.util.BitSet and Java.type("java.util.BitSet") are interchangeable, I just used both to illustrate that no matter how you construct the object, the result should be the same.