Subj : Re: Using reflection with Rhino "beans" To : Ugo Cei From : Igor Bukanov Date : Thu Sep 30 2004 03:26 pm Ugo Cei wrote: > A little question for any Rhino gurus out there. Assuming you have a > Javascript prototype defined like this (and assuming this is sensible, > since my knowledge of JS is quite limited): > > function PropertyHello() { > this.message = "hello world"; > } > > PropertyHello.prototype.sayHello = function() { > return this.message; > } > > would it be possible to have the 'message' property be accessible via > regular Java reflection. In other words, would it be possible to have > this prototype behave like a Javabean: > > public class PropertyHello { > private String message = "hello world"; > public String getMessage() { return message; } > public void setMessage(String m) { message = m; } > } > > In my case, the getter and setter methods would be called via reflection. You need to use JavaAdapter to create Java classes and their instances from JavaScript. For example, given: function PropertyHello() { this.message = "hello world"; } PropertyHello.prototype.getMessage = function() { return this.message; } PropertyHello.prototype.setMessage = function(message) { this.message = message; } var propertyInstance = new PropertyHello() then the following would happen when you execute: var x = JavaAdapter(propertyInstance) 1. Rhino generates Java class with auto-generated name and the following signatures public class SomeAutoGeneratedName { private ... scriptObj; ... public Object getMessage() { return scriptObj.getMessage(); } public void setMessage(Object m) { scriptObj.setMessage(m); } } 2. Rhino construct an instance of SomeAutoGeneratedName initializing scriptObj to the passed propertyInstance. 3. Rhino wraps the constructed Java object into JavaScript cloths so it can be accessed as any other Java object. In particular, you can pass x to Java methods and since SomeAutoGeneratedName has Bean signatures you can also access it from Rhino as bean so x.message would call (after expensive redirections) propertyInstance.getMessage() and x.message = something would call (after even more expensive redirections) propertyInstance.setMessage(something) Note that you have to write explicit getter/setter in JS as JavaAdapter exposes in Java only methods and you can not control type signatures of SomeAutoGeneratedName and they always would contain Object type unless you use JavaAdapter to extend a class / implement interface that provides the necessary signatures. See for details http://www.mozilla.org/rhino/ScriptingJava.html Regards, Igor .