Convert java object to js

Hello everyone,

I'm new to rhino (and to js, I fear) and have a(n) (understanding)
problem
converting java objects to js. Here is my code:

import org.mozilla.javascript.*;
import java.io.*;

public class FirstTry extends ScriptableObject{

	private SecondTry str;

	public String getClassName() {
		return "FirstTry";
	}

	public void jsConstructor(int test) {
		this.str = new SecondTry();
	}

	public SecondTry jsGet_SecondTry() {return str;}

	public FirstTry() {}
}



import org.mozilla.javascript.*;

public class SecondTry extends ScriptableObject {

	public String member = "Hello World";

	public String getClassName() {
		return "SecondTry";
	}

	public SecondTry() {
	}

	public void jsConstructor() {}

	public String jsGet_member () {return member;}
}


import java.io.File;
import java.io.FileReader;

import org.mozilla.javascript.*;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String filename = "firstTry.js";
		Context cx = Context.enter();
		try {
			Scriptable scope = cx.initStandardObjects();
			File file = new File(filename);
			FileReader reader = new FileReader(file);
			ScriptableObject.defineClass(scope, FirstTry.class);
			ScriptableObject.defineClass(scope, SecondTry.class);
			Object result = cx.evaluateReader(scope, reader, "me", 1, null);
			System.out.println(cx.toString(result));
		} catch (Exception e) {
			System.err.println(e.toString());
		}
	}
}

Here is the code of my js- file:

var test = new FirstTry(12);
test.SecondTry.member;

Executing Test simply gives me "undefined". As SecondTry is a subclass
of ScriptableObject, I expected "Hello World" to be the result. Using
Context.toObject or Context.javaToJs in conjunction with java objects,
which are not sublcasses of ScriptableObbject, works pretty well, but
my aim would be a class ThirdTry, attribute of SecondTry (as SecondTry
is an attribute of FirstTry) and derived from ScriptableObject. I want
to be able to write things like:

test.SecondTry.ThirdTry.anAttributeOfThirdTry (as my application
contains of many 1:n relationships)

When I change the content of my js- file to

var test = new SecondTry();
test.member;

it gives me "Hello World" as expected.

So I wonder what I missed in order to get it going.

Regards (and thanks for your help),
Matthias

0
Matthias
7/10/2006 1:53:44 PM
mozilla.dev.tech.js-engine 2040 articles. 0 followers. Post Follow

6 Replies
422 Views

Similar Articles

[PageSpeed] 13

I had the same problem (with host objects in my case) which nobody
seemed to be able to help with.  I fixed it by defining the properties
for the classes that can be returned from the creatable class.  I don't
know if this is the correct thing to do, seems very cumbersome but it
works.

Here's your modified example (play particular attention to the "member"
association with the "getmember" property - I found there were some
restrictions as to what you can call the properties e.g. "value" for
getvalue doesn't work but "Value" for getValue does)

Steve



import org.mozilla.javascript.*;
import java.io.*;

public class FirstTry extends ScriptableObject{

	private SecondTry str;

	public String getClassName() {
		return "FirstTry";
	}

	public void jsConstructor(int test) {
		this.str =3D new SecondTry();
            this.str.defineProperty("member", this.str.getClass(),
ScriptableObject.DONTENUM);
	}

	public SecondTry jsGet_SecondTry() {return str;}

	public FirstTry() {}
}



import org.mozilla.javascript.*;

public class SecondTry extends ScriptableObject {

	public String member =3D "Hello World";

	public String getClassName() {
		return "SecondTry";
	}

	public SecondTry() {
	}

	public void jsConstructor() {}

	public String getmember () {return member;}
}


import java.io.File;
import java.io.FileReader;

import org.mozilla.javascript.*;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String filename =3D "firstTry.js";
		Context cx =3D Context.enter();
		try {
			Scriptable scope =3D cx.initStandardObjects();
			File file =3D new File(filename);
			FileReader reader =3D new FileReader(file);
			ScriptableObject.defineClass(scope,
FirstTry.class);
			Object result =3D cx.evaluateReader(scope, reader,
"me", 1, null);
			System.out.println(cx.toString(result));
		} catch (Exception e) {
			System.err.println(e.toString());
		}
	}
}

=20











-----Original Message-----
From: dev-tech-js-engine-bounces@lists.mozilla.org
[mailto:dev-tech-js-engine-bounces@lists.mozilla.org] On Behalf Of
Matthias
Sent: 10 July 2006 14:54
To: dev-tech-js-engine@lists.mozilla.org
Subject: [RBL] Convert java object to js

Hello everyone,

I'm new to rhino (and to js, I fear) and have a(n) (understanding)
problem
converting java objects to js. Here is my code:

import org.mozilla.javascript.*;
import java.io.*;

public class FirstTry extends ScriptableObject{

	private SecondTry str;

	public String getClassName() {
		return "FirstTry";
	}

	public void jsConstructor(int test) {
		this.str =3D new SecondTry();
	}

	public SecondTry jsGet_SecondTry() {return str;}

	public FirstTry() {}
}



import org.mozilla.javascript.*;

public class SecondTry extends ScriptableObject {

	public String member =3D "Hello World";

	public String getClassName() {
		return "SecondTry";
	}

	public SecondTry() {
	}

	public void jsConstructor() {}

	public String jsGet_member () {return member;}
}


import java.io.File;
import java.io.FileReader;

import org.mozilla.javascript.*;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String filename =3D "firstTry.js";
		Context cx =3D Context.enter();
		try {
			Scriptable scope =3D cx.initStandardObjects();
			File file =3D new File(filename);
			FileReader reader =3D new FileReader(file);
			ScriptableObject.defineClass(scope,
FirstTry.class);
			ScriptableObject.defineClass(scope,
SecondTry.class);
			Object result =3D cx.evaluateReader(scope, reader,
"me", 1, null);
			System.out.println(cx.toString(result));
		} catch (Exception e) {
			System.err.println(e.toString());
		}
	}
}

Here is the code of my js- file:

var test =3D new FirstTry(12);
test.SecondTry.member;

Executing Test simply gives me "undefined". As SecondTry is a subclass
of ScriptableObject, I expected "Hello World" to be the result. Using
Context.toObject or Context.javaToJs in conjunction with java objects,
which are not sublcasses of ScriptableObbject, works pretty well, but
my aim would be a class ThirdTry, attribute of SecondTry (as SecondTry
is an attribute of FirstTry) and derived from ScriptableObject. I want
to be able to write things like:

test.SecondTry.ThirdTry.anAttributeOfThirdTry (as my application
contains of many 1:n relationships)

When I change the content of my js- file to

var test =3D new SecondTry();
test.member;

it gives me "Hello World" as expected.

So I wonder what I missed in order to get it going.

Regards (and thanks for your help),
Matthias

_______________________________________________
dev-tech-js-engine mailing list
dev-tech-js-engine@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-tech-js-engine


0
Steve
7/10/2006 2:13:29 PM
Steve O'Hara wrote:
> I had the same problem (with host objects in my case) which nobody
> seemed to be able to help with.  I fixed it by defining the properties
> for the classes that can be returned from the creatable class.  I don't
> know if this is the correct thing to do, seems very cumbersome but it
> works.
>
> Here's your modified example (play particular attention to the "member"
> association with the "getmember" property - I found there were some
> restrictions as to what you can call the properties e.g. "value" for
> getvalue doesn't work but "Value" for getValue does)
>
> Steve
>

Hello Steve,

first I want to thank you very much for your quick and very usefull
reply! Thanks to your advise I was not only able to get my code running
without any error (I had to type "getMember" instead of "getmember"
though) but also to include a ThirdTry- class- reference inside of
SecondTry and to access its "content" via

test.SecondTry.ThirdTry.someContent.

But I still wonder, if there's an easier way to do achieve that. I read
in an older posting, that Rhino is expected to convert objects, which
are derived from SciptableObject and instantiated in Java, to js
automatically and in a way I expected my example program to behave.
That would be straightforward. Perhaps anyone else was able to solve a
problem similar to mine in a more "easy" way and could give some hints.

Regards,
Matthias

0
Matthias
7/10/2006 3:59:04 PM
=20
Hi Mathias

I agree - you would have thought that this problem would have come up a
lot with developers.
I spent a full day figuring out that this was the solution...  It would
be nice if someone at Mozilla could confirm that this is the correct
approach.

Once I'd solved the problem, I then wrote a useful method for adding all
the public methods and properties automatically using reflection.
I then just call the method with my scriptable object and it adds all
properties and functions automatically for me.

Hope this is useful.

Steve



public static void createMethods(ScriptableObject objValue) {

    // Use reflection to get all the public methods and "getter/setter"
properties

    Method[] objMeths =3D objValue.getClass().getMethods();
    if (objMeths!=3Dnull) {
        HashSet objFuncs =3D new HashSet();
        HashSet objProps =3D new HashSet();
        for (int iCnt=3D0; iCnt<objMeths.length; iCnt++) {
            if (Modifier.isPublic(objMeths[iCnt].getModifiers()) &&
=20
objMeths[iCnt].getDeclaringClass().equals(objValue.getClass())) {
                if (objMeths[iCnt].getName().startsWith("get") ||=20
                    objMeths[iCnt].getName().startsWith("set")) {
                    objProps.add(objMeths[iCnt].getName().substring(3));
                }
                else {
                    objFuncs.add(objMeths[iCnt].getName());
                }
            }
        }

        // Now define these in the scope

        if (!objFuncs.isEmpty()) {
            String[] asFuncs =3D (String[])objFuncs.toArray(new
String[0]);
            objValue.defineFunctionProperties(asFuncs,
objValue.getClass(),=20
=20
ScriptableObject.DONTENUM);}
        if (!objProps.isEmpty()) {
            for (Iterator objProp=3DobjProps.iterator();
objProp.hasNext();) {
                objValue.defineProperty((String)objProp.next(),
objValue.getClass(),=20
                                        ScriptableObject.DONTENUM);}
        }
    }
}


-----Original Message-----
From: dev-tech-js-engine-bounces@lists.mozilla.org
[mailto:dev-tech-js-engine-bounces@lists.mozilla.org] On Behalf Of
Matthias
Sent: 10 July 2006 16:59
To: dev-tech-js-engine@lists.mozilla.org
Subject: [RBL] Re: Convert java object to js

Steve O'Hara wrote:
> I had the same problem (with host objects in my case) which nobody
> seemed to be able to help with.  I fixed it by defining the properties
> for the classes that can be returned from the creatable class.  I
don't
> know if this is the correct thing to do, seems very cumbersome but it
> works.
>
> Here's your modified example (play particular attention to the
"member"
> association with the "getmember" property - I found there were some
> restrictions as to what you can call the properties e.g. "value" for
> getvalue doesn't work but "Value" for getValue does)
>
> Steve
>

Hello Steve,

first I want to thank you very much for your quick and very usefull
reply! Thanks to your advise I was not only able to get my code running
without any error (I had to type "getMember" instead of "getmember"
though) but also to include a ThirdTry- class- reference inside of
SecondTry and to access its "content" via

test.SecondTry.ThirdTry.someContent.

But I still wonder, if there's an easier way to do achieve that. I read
in an older posting, that Rhino is expected to convert objects, which
are derived from SciptableObject and instantiated in Java, to js
automatically and in a way I expected my example program to behave.
That would be straightforward. Perhaps anyone else was able to solve a
problem similar to mine in a more "easy" way and could give some hints.

Regards,
Matthias

_______________________________________________
dev-tech-js-engine mailing list
dev-tech-js-engine@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-tech-js-engine


0
Steve
7/10/2006 4:20:28 PM
Hi Steve,

your method seems to be very useful!
I deeply support your question to mozilla referring to that "converting
problem" and hope for a resolving answer.

Regards,
Matthias

0
Matthias
7/11/2006 7:59:01 AM
Still having the problem stated above I run the Rhino debugger for the
following js- script using the original classes (e.g. not modified in
the way, Steve recommeneded in order to get it going).

var test = new FirstTry();
var sec = test.SecondTry;

While test has [object FirstTry] as its value, sec has: TypeError:
Cannot find default value for object.

Evaluating

var sec = new SecondTry();

works as expected. The value of sec now is [object SecondTry].

I still think that there's a converting problem but I still don't
understand, why and how I can resolve that.

Regards,
Matthias

0
Matthias
7/12/2006 1:52:57 PM
Well, me again ;-)...

I think I can give an "indirect" answer to the problem above. See

http://groups.google.com/group/netscape.public.mozilla.jseng/browse_thread/thread/353f990416147308/e9898fa4cb541cc7?q=host+object&rnum=47#e9898fa4cb541cc7

As I assumed thinking my problem over and over again the js-
Constructor for SecondTry is never called in my scenario (debugging my
code approved that). There's only a call to the java constructor of
SecondTry.

What confirms me that this is the answer to the question/problem is the
fact that running

var test = new FirstTry();
var sec = test.SecondTry;

now gives me [object SecondTry] as the value of sec.

Regards,
Matthias

0
Matthias
7/12/2006 2:41:43 PM
Reply:

Similar Artilces:

convert java object to js
Hello everyone, I'm new to rhino (and js ;-)) and have a(n) (understanding) problem converting java objects to js. Here is my code: import org.mozilla.javascript.*; import java.io.*; public class FirstTry extends ScriptableObject{ private SecondTry str; public String getClassName() { return "FirstTry"; } public void jsConstructor(int test) { this.str = new SecondTry(); } public SecondTry jsGet_SecondTry() {return str;} public FirstTry() {} } import org.mozilla.javascript.*; public class SecondTry extends ScriptableObject { p...

Call js from 1 js to other js
Hi to all developers, I have two javascript file 1 Validation.js 2 Date.js there are some functions in the file I wanted to know how can i add the reference of Date.js file in Validation.js . because if i want to call a function of date.js in validation.js then i need to copy the function from date.js and paste it in validation.js to work   help me..     Imran Khan You can't copy pieces of one into the other. You'd need to include both files into the page. NC...   Once both the files are included onto the page, every function is accessibl...

superreview requested: [Bug 410946] Crash in JS engine aborting applet making Java/JS calls : [Attachment 305554] Fix.
Johnny Stenback (:jst) <jst@mozilla.org> has asked Boris Zbarsky (reviews very slow until May) <bzbarsky@mit.edu> for superreview: Bug 410946: Crash in JS engine aborting applet making Java/JS calls https://bugzilla.mozilla.org/show_bug.cgi?id=410946 Attachment 305554: Fix. https://bugzilla.mozilla.org/attachment.cgi?id=305554&action=edit ------- Additional Comments from Johnny Stenback (:jst) <jst@mozilla.org> See previous comment for description of what this does. ...

superreview granted: [Bug 410946] Crash in JS engine aborting applet making Java/JS calls : [Attachment 305554] Fix.
Boris Zbarsky (reviews very slow until May) <bzbarsky@mit.edu> has granted Johnny Stenback (:jst) <jst@mozilla.org>'s request for superreview: Bug 410946: Crash in JS engine aborting applet making Java/JS calls https://bugzilla.mozilla.org/show_bug.cgi?id=3D410946 Attachment 305554: Fix. https://bugzilla.mozilla.org/attachment.cgi?id=3D305554&action=3Dedit ------- Additional Comments from Boris Zbarsky (reviews very slow until May) <bzbarsky@mit.edu> Could you add documentation to nsIObjectFrame which says which of the metho= ds might destroy the frame? ...

superreview granted: [Bug 410946] Crash in JS engine aborting applet making Java/JS calls : [Attachment 306220] Updated diff, ready to land.
Johnny Stenback (:jst) <jst@mozilla.org> has granted superreview: Bug 410946: Crash in JS engine aborting applet making Java/JS calls https://bugzilla.mozilla.org/show_bug.cgi?id=410946 Attachment 306220: Updated diff, ready to land. https://bugzilla.mozilla.org/attachment.cgi?id=306220&action=edit ------- Additional Comments from Johnny Stenback (:jst) <jst@mozilla.org> Updated fix, fixes all of the above. Boris, the only real difference here is how nsPluginDestroyRunnable works, it's now a PRCList with a static list head so that when we run one of these we ca...

creating JS objects in Java...?
So, if I use the JavaAdapter to make c new javascript class that inherits from another class an implements a few interfaces, if I use the Rhino API to get a hold of that object in Java, can I use it right then and there as an object of those interface types? Or do I have to use it as such only in the JS context? Here's what I want to do: I have an engine that takes Module objects. Many of these Module objects have been overwritten in Java - EmailModule, etc. I would like to be able to have the user author his own Module using JavaScript, using, presumably, the JavaAdapt...

Persistent pointers to JS::Object vis JS::Handle API
Imagine if you will a C++ class that encapsulates an instance of a SpiderMonkey JS interpreter. This class would start out something like this: class JSContainer { public: JSContainer(); private: JSRuntime *runtime; JSContext *context; JSObject *global; }; In JSContainer() I run up against a problem with respect to HandleObject parameters, for example JSContainer::JSContainer() { this->runtime = JS_NewRuntime(64L * 1024L * 1024L); this->context = JS_NewContext(runtime,8192); t...

superreview granted: [Bug 275107] Some JS Strict warnings (In am-server.js, am-server-advanced.js, am-serverwithnoidentities.js) : [Attachment 168993] (Av1) <am-server*.js>
Dan Mosedale <dmose@mozilla.org> has granted Serge GAUTHERIE <gautheri@noos.fr>'s request for superreview: Bug 275107: Some JS Strict warnings (In am-server.js, am-server-advanced.js, am-serverwithnoidentities.js) https://bugzilla.mozilla.org/show_bug.cgi?id=275107 Attachment 168993: (Av1) <am-server*.js> https://bugzilla.mozilla.org/attachment.cgi?id=168993&action=edit ------- Additional Comments from Dan Mosedale <dmose@mozilla.org> sr=dmose ...

superreview granted: [Bug 275107] Some JS Strict warnings (In am-server.js, am-server-advanced.js, am-serverwithnoidentities.js) : [Attachment 169134] (Bv1) <am-serverwithnoidentities.js>
Dan Mosedale <dmose@mozilla.org> has granted Serge GAUTHERIE <gautheri@noos.fr>'s request for superreview: Bug 275107: Some JS Strict warnings (In am-server.js, am-server-advanced.js, am-serverwithnoidentities.js) https://bugzilla.mozilla.org/show_bug.cgi?id=275107 Attachment 169134: (Bv1) <am-serverwithnoidentities.js> https://bugzilla.mozilla.org/attachment.cgi?id=169134&action=edit ------- Additional Comments from Dan Mosedale <dmose@mozilla.org> sr=dmose ...

Use js/TypeDecls.h for basic JS engine type declarations
Hi, In a recent thread ("Stop #including jsapi.h everywhere!"), I wrote the following. > Next time you're thinking of adding a |#include "jsapi.h"| statement, > please think about whether a forward declaration would suffice -- i.e. > if you are only using public JS types (i.e. not functions), and only > using them as pointers, references, or parameters in function > declarations. (Forward-declaring JS_PUBLIC_API types is harder; ask > me for help if you need to do that.) > > [BTW, you might think "these popular forward declar...

Creating pure Java objects from Rhino JS
Hi, Is it possible to create Java objects (that don't extend ScriptableObject and dont belong to the java or javax packages) from the Rhino Javascript code? Thanks, Sai Arial Winds wrote: > Hi, > Is it possible to create Java objects (that don't extend > ScriptableObject and dont belong to the java or javax packages) from > the Rhino Javascript code? > > Thanks, > Sai What do you mean by "create?" If all you mean is instantiate, then sure. Basically, if class foo.bar.Baz is in the classpath, you can do: var myBaz = new Pac...

newbie : Can you typecast Java object in JS? if yes, how?
Can you typecast Java object in JS? if yes, how? - Meghana _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ ...

Where are hierArrays.js and hierMenus.js?
I'm new to EAServer and am trying to connect to the database for the first time. Each time I try, the personal web server would indicate that it's unable to locate hierArrays.js and hierMenus.js with a 404 error. The database is ASA 6.0, EA Server 3.5, Dynamo Personal Web Server. Thanks 404 means it cannot find the page. After you added a mapping, did you restart the PWS? -- Larry Cermak [Team Sybase] Corporate Technology Partners, Inc. www.ctpartners.com Web DataWindow Articles http://sdn.sybase.com/sdn/appdev/get_doc.stm?loc=1001708 Choo Beng wrote in me...

User.js or prefs.js
I looked in my profile's folder, and I only have a prefs.js, I do not have a user.js. Why is that? On 21.01.2007 13:01, Trel Smith wrote: --- Original Message --- > I looked in my profile's folder, and I only have a prefs.js, I do not > have a user.js. Why is that? Because you didn't create one, it's user created not automatic. -- Jay Garcia Netscape/Mozilla Champion UFAQ - http://www.UFAQ.org Trel Smith wrote: > I looked in my profile's folder, and I only have a prefs.js, I do not > have a user.js. Why is that? its a self created ...

Web resources about - Convert java object to js - mozilla.dev.tech.js-engine

File:Convert to SVG and move to Commons.svg - Wikipedia, the free encyclopedia
As a courtesy (but not a requirement), please e-mail me or leave a note on my talk page if you use this image outside of Wikipedia. Thanks! As ...

Facebook Co-Founder Dustin Moskovitz Sells 450K Shares, Converts 7M More
The great Facebook stock sale frenzy continues on with a report that Co-Founder Dustin Moskovitz unloaded 450,000 shares in the social network ...

Facebook Announces “App2User” Liquidity Program for Merchants to Convert Rewards Points into Credits
... for Credits, just announced a new Credits program called “App2User,” designed to enable merchants and loyalty program operators to convert their ...

How to Convert Leads Into Buying Customers - The 9 Step Sales Process EVERYONE Should Use
... School of Business in Toronto on the topics of Sales and Entrepreneurship. I shared with them the sales process that I find How to Convert Leads ...

Bitcoin : Should I convert my savings to Bitcoin?
Answer (1 of 7): You should think of this question as "Should I invest all my savings in Bitcoin?", and not "Should I have my savings denominated ...

Convertizo 2 - Convert Units and Currency in Style on the App Store on iTunes
Get Convertizo 2 - Convert Units and Currency in Style on the App Store. See screenshots and ratings, and read customer reviews.

Catholics should not convert Jews, says Vatican, in push against anti-Semitism
... 50 years since the Vatican's repudiation of the concept of Jewish guilt for Jesus' death.  Vatican City: Catholics should not try to convert ...

Opinion: These 5 things made me a happy iPad Pro convert
... like I needed a bigger device. But after three weeks with my iPad Pro, several things have changed my mind, and I’m officially a happy convert ...

Today’s apps gone free: BlockBear, Stock Grader, PDF Smart Convert and more
Block ads and other annoying content, take the emotion out of investing, and convert almost anything into a PDF with todays collection of apps ...

How to convert your old VHS tapes to DVD with this software
Remember those old VHS tapes you have sitting in the corner? Convert them into DVDs with this affordable software so you can easily watch them ...

Resources last updated: 12/22/2015 5:54:06 PM