Safe way of checking if object is instance of Java class

947 views
Skip to first unread message

Tim Fox

unread,
Mar 1, 2012, 11:01:30 AM3/1/12
to mozill...@googlegroups.com
I need to check, in JavaScript, whether an object is an instance of a
Java class, I'm doing this by checking if it has the 'getClass' function:

if (typeof obj.getClass != "undefined") {
// It's a Java object
}

Which seems to work, but not sure if it's foolproof.

Is there a better way of doing this?

Jacob Beard

unread,
Mar 1, 2012, 1:30:17 PM3/1/12
to mozill...@googlegroups.com
I could see this as being problematic if you have a js object with a
property called "getClass", e.g.

{getClass : true}

Would fail your test

I think using instanceof to check against java.lang.Object would be
safer. For example:

js> x={}
[object Object]
js> y=new Packages.java.lang.Object()
java.lang.Object@2bb514
js> z= new Packages.java.lang.String("foo");
foo
js> x instanceof Packages.java.lang.Object
false
js> "hello" instanceof Packages.java.lang.Object
false
js> y instanceof Packages.java.lang.Object
true
js> z instanceof Packages.java.lang.Object
true
js>

Jake

Reply all
Reply to author
Forward
0 new messages