Jump to content
  • Advertisement
Sign in to follow this  
sws26

[java] Java and Beanshell

This topic is 4229 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there any way to achieve the following using BeanShell:
public class ScriptableObject {

  private int someProperty;
  private Interpreter bsh;
  private String scriptText;

  public void scriptableMethod(){
    bsh.eval(scriptText;);
  }
}



Now is there anyway I can get the interpreter to be namespaced such that I can access private variables of ScriptableObject as if they were local and have "this" refer to the ScriptableObject instance?

Share this post


Link to post
Share on other sites
Advertisement
Unless you use some crazy automatic-code-generation system, I don't think there is a way to do what you want. Java classes aren't dynamic, you can't add members on the fly like you can with some other languages.

By the way, I find that the best way for crossing the Java-script boundary is to write a Java interface and implement it in script. Unfortunately you'd have to write getters and setters for all the variables you want to access.

Share this post


Link to post
Share on other sites
I don't expect the java classes to be dynamic but I am hoping that sort of behavior can
be implemented from the BeanShell interpreter. I can do something like this by adding
getters and setters for all the private variables and then putting the object in the
interpreter with a name like "me" or "self".

This means the scripts look like:

val = me.someProperty;
val++;
me.someProperty = val;
me.someMethod();


BeanShell will automagically convert the assignment into get/set where appropriate but
I would really like to get rid of the "me" reference.

Share this post


Link to post
Share on other sites
Ohhhhh I see, I guess I had it backwards.

I guess one solution would be to have your scripted code be a subclass of your Java class. That way you don't need to write "me" or "self", because they would be the same object. You wouldn't be able to read private vars though, you'd have to change those to protected.

Share this post


Link to post
Share on other sites
Found a reasonable workaround. There is an undocumented feature in beanshell importObject() that does most of what I am after (can't access private/protected anything but don't need the me).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!