### desktop() Source: https://github.com/beanshell/beanshell/wiki/Commands Starts the BeanShell GUI desktop in a JFrame and initializes a starter workspace. ```APIDOC ## desktop() ### Description Starts the BeanShell GUI desktop in a JFrame. A starter workspace is created and added to the desktop. ``` -------------------------------- ### Start Remote Session from Java Source: https://github.com/beanshell/beanshell/wiki/Remote-Server-Mode Initializes an interpreter, exposes application objects, and starts the server programmatically. ```java // Java code import bsh.Interpreter; i = new Interpreter(); i.set( "myapp", this ); // Provide a reference to your app i.set( "portnum", 1234 ); i.eval("setAccessibility(true)"); // turn off access restrictions i.eval("server(portnum)"); ``` -------------------------------- ### Build the project Source: https://github.com/beanshell/beanshell/blob/master/README.md Use Maven to clean and install the project dependencies and artifacts. ```shell $ mvn clean install ``` -------------------------------- ### server Source: https://github.com/beanshell/beanshell/wiki/Commands Starts a remote BeanShell listener service. ```APIDOC ## void server( int port ) ### Description Create a remote BeanShell listener service attached to the current interpreter, listening on the specified port. ### Parameters - **port** (int) - Required - The port number to listen on. ``` -------------------------------- ### Build BeanShell from source Source: https://github.com/beanshell/beanshell/blob/master/README.md Use Maven to install the project from the master branch. ```shell $ mvn install ``` -------------------------------- ### BeanShell Scripting Examples Source: https://github.com/beanshell/beanshell/wiki/Quickstart Demonstrates variable assignment, loops, and GUI component creation using BeanShell's loosely typed syntax. ```java foo = "Foo"; four = (2 + 2)*2/2; print( foo + " = " + four ); // print() is a BeanShell command // Do a loop for (i=0; i<5; i++) print(i); // Pop up a frame with a button in it button = new JButton( "My Button" ); frame = new JFrame( "My Frame" ); frame.getContentPane().add( button, "Center" ); frame.pack(); frame.setVisible(true); ``` -------------------------------- ### Java 'this' reference example Source: https://github.com/beanshell/beanshell/wiki/Scripted-objects Demonstrates the standard Java usage of 'this' to return a reference to the current object instance. ```java // MyClass.java MyClass { Object getObject() { return this; // return a reference to our object } } ``` -------------------------------- ### Enable Remote Server Source: https://github.com/beanshell/beanshell/wiki/Remote-Server-Mode Starts the BeanShell HTTP and telnet session servers on the specified port. ```java server(1234); // Httpd started on port: 1234 // Sessiond started on port: 1235 ``` -------------------------------- ### Implementing an eval command Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Example of using 'this.caller.namespace' to evaluate code in the caller's context. ```java eval("a=5"); print( a ); // 5 ``` ```java eval( String text ) { this.interpreter.eval( text, this.caller.namespace ); } ``` -------------------------------- ### Manage Complex Variables with set() and get() Source: https://github.com/beanshell/beanshell/wiki/Embedding-BeanShell-in-Your-Application Demonstrates using set and get to interact with complex object fields and array indices. ```java import bsh.Interpreter; i=new Interpreter(); i.eval("myobject=object()" ); i.set("myobject.bar", 5); i.eval("ar=new int[5]"); i.set("ar[0]", 5); i.get("ar[0]"); ``` -------------------------------- ### Start BeanShell interactive shell Source: https://github.com/beanshell/beanshell/blob/master/README.md Launch the interactive interpreter using the Java command and the classpath. ```shell $ java -cp bsh-2.1.1.jar bsh.Interpreter ``` -------------------------------- ### Scripted Class with Loose Code Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Example demonstrating how loose code outside the class definition is executed upon class initialization. ```java // Begin script Foo.bsh class Foo { public static void main( String [] args ) { } } message = "Hey"; message += " you!"; num = 2 * 2; message += " The answer is: "+num; // end script Foo.bsh ``` -------------------------------- ### Run BeanShell Standalone Source: https://github.com/beanshell/beanshell/wiki/Modes-of-Operation Execute scripts or start an interactive session using the bsh.Interpreter class. ```java java bsh.Interpreter [ filename ] [ arg ] [ ... ] // Run a script file ``` ```java java bsh.Interpreter // Run interactively on the command line ``` -------------------------------- ### Define a Scripted Class Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Example of a basic scripted class definition in BeanShell. ```java class Foo { Foo() { print("I'm being constructed!"); } } ``` -------------------------------- ### Example BshDoc XML output Source: https://github.com/beanshell/beanshell/wiki/BshDoc The generated XML structure contains file-level and method-level information, including signatures and comment text. ```xml foo doFoo doFoo ( int x ) <![CDATA[ doFoo() method comment. ]]> <![CDATA[ foo file comment. ]]> ``` -------------------------------- ### Closure and Block Scoping Example Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Illustrates the scoping behavior where 'this' refers to the nearest enclosing method or root scope, even within nested blocks. ```java myMethod() { if ( true ) { /* inside block */ } else { /* */ } { /* gratuitous block */ } } ``` -------------------------------- ### Load and execute custom commands Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Add a directory to the classpath and import the commands for use. ```java addClassPath("/home/pat"); // If it's not already in our classpath importCommands("/mycommands"); ``` ```java helloWorld(); // prints "Hello World!" ``` -------------------------------- ### Implementing a Basic SecurityGuard Source: https://github.com/beanshell/beanshell/wiki/SecurityGuard Shows the boilerplate for implementing the SecurityGuard interface and registering it with the BeanShell Interpreter. ```java import bsh.Interpreter; import bsh.security.SecurityGuard; public class Main { public static void main(String[] args) throws Throwable { // This is your implementation of SecurityGuard class MySecurityGuard implements SecurityGuard {} // Add your SecurityGuard to be used by the Interpreter Interpreter.mainSecurityGuard.add(new MySecurityGuard()); // Create an interpreter instance an evaluate the code Interpreter interpreter = new Interpreter(); interpreter.eval("... code to be evaluated"); } } ``` -------------------------------- ### Execute standard Java syntax Source: https://github.com/beanshell/beanshell/wiki/Basic-syntax Demonstrates using standard Java variable declarations, method calls, and loops within BeanShell. ```java /* Standard Java syntax */ // Use a hashtable Hashtable hashtable = new Hashtable(); Date date = new Date(); hashtable.put( "today", date ); // Print the current clock value print( System.currentTimeMillis() ); // Loop for (int i=0; i<5; i++) print(i); // Pop up a frame with a button in it JButton button = new JButton( "My Button" ); JFrame frame = new JFrame( "My Frame" ); frame.getContentPane().add( button, "Center" ); frame.pack(); frame.setVisible(true); ``` -------------------------------- ### Demonstrating method scope context Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Illustrates the difference between 'super' (definition context) and 'this.caller' (usage context). ```java foo() { ... } foo(); ``` ```java foo() { bar() { ... } ... } // somewhere fooObject.bar(); ``` -------------------------------- ### Scripted Class with Variable Initialization Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Example of a scripted class that utilizes external variables within its constructor. ```java welcomeMessage = "Hello World!"; class Foo { Foo() { print( "I'm being constructed: "+ welcomeMessage ); } } ``` -------------------------------- ### Importing BeanShell Commands Source: https://github.com/beanshell/beanshell/wiki/Commands Demonstrates importing scripted or compiled commands using package or path notation, and adding custom JARs to the classpath. ```beanshell // equivalent importCommands("/bsh/commands") importCommands("bsh.commands") ``` ```beanshell addClassPath("mycommands.jar"); importCommands("/mypackage/commands"); ``` -------------------------------- ### Synchronized blocks and methods Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Examples of using the synchronized modifier on methods and blocks, which lock the parent namespace's This reference. ```java // The following synchronize on the same lock synchronized ( this ) { } // block synchronized int foo () { } // method foo synchronized int bar () { } // method bar int gee() { synchronized( super ) { } // inside gee() } ``` -------------------------------- ### Execute BeanShell User Interface Source: https://github.com/beanshell/beanshell/blob/master/README.md Run the BeanShell UI using the downloaded JAR file. ```shell $ java -jar bsh-2.1.1.jar ``` -------------------------------- ### Handling Path Slashes Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Demonstrates the use of forward slashes for cross-platform compatibility and escaped backslashes for Windows paths. ```java dir("c:/Windows"); // ok dir("c:\\Windows"); // ok ``` -------------------------------- ### Run the BeanShell Test Suite Source: https://github.com/beanshell/beanshell/blob/master/src/test/resources/README.txt Execute the test suite using the BeanShell interpreter from the command line. ```bash java bsh.Interpreter RunAllTests.bsh ``` -------------------------------- ### run Source: https://github.com/beanshell/beanshell/wiki/Commands Runs a command in its own private global namespace. ```APIDOC ## run( String filename, Object runArgument ) ## run( String filename ) ### Description Run a command in its own private global namespace, with its own class manager and interpreter context. ### Parameters - **filename** (String) - Required - The file to run. - **runArgument** (Object) - Optional - An argument passed to the child context. ``` -------------------------------- ### Evaluate Scripts with eval() Source: https://github.com/beanshell/beanshell/wiki/Embedding-BeanShell-in-Your-Application Demonstrates evaluating script strings and reading scripts from streams. ```java Object result = i.eval( "long time = 42; new Date( time )" ); // Date Object result = i.eval("2*2"); // Integer ``` ```java reader = new FileReader("myscript.bsh"); i.eval( reader ); ``` -------------------------------- ### Import static methods and fields Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Demonstrates importing static members from a Java class into the BeanShell namespace. ```java static import java.lang.Math.*; sqrt(4.0); ``` -------------------------------- ### Use show() for interactive debugging Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md The show() command enables automatic printing of expression results in interactive mode, replacing manual print statements. ```java print( myObject instanceof Blah ); print( myObject.getFoo() ); print( myObject.somethingElse() ); ``` ```java show(); myObject instanceof Blah; myObject.getFoo(); myObject.somethingElse(); ``` -------------------------------- ### Import commands from Java packages Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Commands can be imported using package notation or resource paths. ```java // equivalent importCommands("com.xyz.utils"); importCommands("/com/xyz/utils"); ``` -------------------------------- ### Array Creation with Auto-casting Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Demonstrates support for auto-casting in array initializers for various primitive types. ```java long [] la = { 1, 2 }; float [] fa = { 1, 2 }; byte [] ba = { 1, 2 }; ``` -------------------------------- ### exit() Source: https://github.com/beanshell/beanshell/wiki/Commands Conditionally exits the virtual machine. ```APIDOC ## exit() ### Description Conditionally exit the virtual machine. Calls System.exit(0) unless bsh.system.shutdownOnExit is set to false. ``` -------------------------------- ### editor() Source: https://github.com/beanshell/beanshell/wiki/Commands Opens a GUI editor, either as a standalone frame from the command line or as a workspace editor within the GUI desktop. ```APIDOC ## editor() ### Description Open a GUI editor from the command line or in the GUI desktop mode. ``` -------------------------------- ### Execute remote scripts via command line Source: https://github.com/beanshell/beanshell/wiki/Servlet-Mode Use the bsh.Remote launcher to send a local script file to the servlet for evaluation. ```sh java bsh.Remote http://localhost:8080/bshservlet/eval test1.bsh ``` -------------------------------- ### Connect an Interpreter to JConsole Source: https://github.com/beanshell/beanshell/wiki/FAQ Initialize a BeanShell interpreter with a JConsole instance and execute it. ```java Interpreter interpreter = new Interpreter( console ); interpreter.run(); ``` -------------------------------- ### Execute Dynamically Typed Methods Source: https://github.com/beanshell/beanshell/wiki/Scripted-methods Demonstrate how dynamic methods handle different data types like integers and strings. ```java foo = add(1, 2); print( foo ); // 3 foo = add("Oh", " baby"); print( foo ); // Oh baby ``` -------------------------------- ### Import Java classes and packages Source: https://github.com/beanshell/beanshell/wiki/Basic-syntax Standard Java import syntax is used to bring classes into the current scope. ```java // Standard Java import javax.xml.parsers.*; import mypackage.MyClass; ``` -------------------------------- ### workspaceEditor Source: https://github.com/beanshell/beanshell/wiki/Commands Initializes a new workspace editor. ```APIDOC ## workspaceEditor( Interpreter parent, String name ) ### Description Creates a new workspaceEditor associated with a workspace and places it on the desktop. ### Parameters - **parent** (bsh.Interpreter) - Required - The parent interpreter instance. - **name** (String) - Required - The name of the workspace editor. ``` -------------------------------- ### Retrieve methods with getMethods() Source: https://github.com/beanshell/beanshell/wiki/Reflective-Style-Access Use the namespace getMethods() method to obtain an array of bsh.BshMethod objects representing all defined methods. ```java foo() { ... } foo( int a ) { ... } bar( int arg1, String arg2 ) { ... } print ( this.namespace.getMethods() ); // Array: [Lbsh.BshMethod;@291aff { // Bsh Method: bar // Bsh Method: foo // Bsh Method: foo // } ``` -------------------------------- ### Handle exceptions Source: https://github.com/beanshell/beanshell/wiki/Basic-syntax Demonstrates standard and loosely typed exception handling using try/catch blocks. ```java try { int i = 1/0; } catch ( ArithmeticException e ) { print( e ); } ``` ```java try { ... } catch ( e ) { print( "caught exception: "+e ); } ``` -------------------------------- ### Connect Interpreter to JConsole Source: https://github.com/beanshell/beanshell/wiki/Using-JConsole Initialize an Interpreter with a JConsole instance and run it in a separate thread. ```java Interpreter interpreter = new Interpreter( console ); new Thread( interpreter ).start(); // start a thread to call the run() method ``` -------------------------------- ### Configure BshServlet in web.xml Source: https://github.com/beanshell/beanshell/wiki/Servlet-Mode Add this configuration to your web application's web.xml to deploy the BshServlet. ```xml bshservlet bsh.servlet.BshServlet bshservlet /eval ``` -------------------------------- ### Swap Namespaces with setNameSpace Source: https://github.com/beanshell/beanshell/wiki/Commands Demonstrates how to switch the current execution context between different object namespaces. ```beanshell fooState = object(); barState = object(); print(this.namespace); setNameSpace(fooState.namespace); print(this.namespace); a=5; setNameSpace(barState.namespace); print(this.namespace); a=6; setNameSpace(fooState.namespace); print(this.namespace); print(a); // 5 setNameSpace(barState.namespace); print(this.namespace); print(a); // 6 ``` -------------------------------- ### Invoke BeanShell via BSFManager Source: https://github.com/beanshell/beanshell/wiki/BSF-Bean-Scripting-Framework Demonstrates registering the BeanShell engine with BSFManager and executing a script with bean declarations. ```java import org.apache.bsf.*; public class TestBshBSF { public static void main( String [] args ) throws BSFException { BSFManager mgr = new BSFManager(); // register beanshell with the BSF framework String [] extensions = { "bsh" }; mgr.registerScriptingEngine( "beanshell", "bsh.util.BeanShellBSFEngine", extensions ); mgr.declareBean("foo", "fooString", String.class); mgr.declareBean("bar", "barString", String.class); mgr.registerBean("gee", "geeString"); BSFEngine beanshellEngine = mgr.loadScriptingEngine("beanshell"); String script = "foo + bar + bsf.lookupBean(\"gee\")"; Object result = beanshellEngine.eval( "Test eval...", -1, -1, script ); System.out.println(result); // fooStringbarStringgeeString } } ``` -------------------------------- ### Define a BeanShell command script Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Create a command by defining a method in a file named after the command. ```java // File: helloWorld.bsh helloWorld() { print("Hello World!"); } ``` -------------------------------- ### Change to script directory using dirname Source: https://github.com/beanshell/beanshell/wiki/Commands Use pathToFile() to localize the path relative to the working directory before using dirname() to extract the directory portion. ```beanshell // Change to the directory containing this script path=pathToFile( getSourceFileInfo() ).getAbsolutePath(); cd( dirname( path ) ); ``` -------------------------------- ### Invoke BeanShell Interpreter with Arguments Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Demonstrates how to pass command-line arguments to a BeanShell script, which are then accessible via the bsh.args array. ```bash java bsh.Interpreter MyClass foo bar ``` -------------------------------- ### Importing commands Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Using importCommands() to load scripted or compiled commands from specific package paths. ```java // equivalent importCommands("/bsh/commands") importCommands("bsh.commands") importCommands("/mypackage/commands") ``` -------------------------------- ### Run BeanShell Modes Source: https://github.com/beanshell/beanshell/wiki/Quickstart Commands to launch the BeanShell graphical console, text-only interpreter, or execute a script file. ```bash java bsh.Console // run the graphical desktop ``` ```bash java bsh.Interpreter // run as text-only on the command line ``` ```bash java bsh.Interpreter filename [ args ] // run script file ``` -------------------------------- ### classBrowser Source: https://github.com/beanshell/beanshell/wiki/Commands Opens the class browser. ```APIDOC ## classBrowser() ### Description Open the class browser. ``` -------------------------------- ### source Source: https://github.com/beanshell/beanshell/wiki/Commands Reads and evaluates a script from a file or URL. ```APIDOC ## source ### Description Read a file or URL into the interpreter and evaluate it in the current namespace. ### Signature - Object source(String filename) - Object source(URL url) ``` -------------------------------- ### Static Import Syntax Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Updated syntax for static imports, matching Java 5 standards. ```java import static Foo.*; ``` -------------------------------- ### Find class source with which Source: https://github.com/beanshell/beanshell/wiki/Commands Locate the source of a class file using the classpath. Note that the command currently only reports the first occurrence. ```java print( getResource("/com/foo/MyClass.class") ); // Same as... // System.out.println( // getClass().getResourceAsStream("/com/foo/MyClass.class" ) ); ``` -------------------------------- ### Using invoke meta-method Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Defining the invoke() meta-method directly in scope to handle missing method calls. ```java invoke( String methodName, Object [] arguments ) { ... } // invoke() will be called to handle noSuchMethod() noSuchMethod("foo"); ``` -------------------------------- ### Access via Telnet Source: https://github.com/beanshell/beanshell/wiki/Remote-Server-Mode Connects to the BeanShell command line using a standard telnet client. ```bash telnet ``` -------------------------------- ### Auto-allocate variables using property style Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Assign values to compound names to automatically create scripted objects, similar to properties files. ```java // foo is initially undefined foo.bar.gee = 42; print( foo.bar.gee ); // 42 print( foo.bar ); //'this' reference (XThis) to Bsh object: auto: bar print( foo ); //'this' reference (XThis) to Bsh object: auto: foo ``` -------------------------------- ### clear Source: https://github.com/beanshell/beanshell/wiki/Commands Clears all variables, methods, and imports from the current namespace. ```APIDOC ## clear() ### Description Clear all variables, methods, and imports from this namespace. If this namespace is the root, it will be reset to the default imports. ``` -------------------------------- ### Configure Classpath for BeanShell Source: https://github.com/beanshell/beanshell/wiki/Quickstart Commands to add the BeanShell JAR to the system classpath on Unix and Windows environments. ```bash export CLASSPATH=$CLASSPATH:bsh-xx.jar ``` ```batch set classpath=%classpath%;bsh-xx.jar ``` -------------------------------- ### pathToFile(String filename) Source: https://github.com/beanshell/beanshell/wiki/Commands Creates a File object relative to the current working directory. ```APIDOC ## pathToFile(String filename) ### Description Creates a File object corresponding to the specified file path name, taking into account the BeanShell current working directory (bsh.cwd). ### Parameters - **filename** (String) - Required - The file path to resolve. ``` -------------------------------- ### Locate a Class in the Classpath Source: https://github.com/beanshell/beanshell/wiki/Basic-syntax Uses the which() command to identify the location of a specific class within the mapped classpath. ```text bsh % which( java.lang.String ); Jar: file:/usr/java/j2sdk1.4.0/jre/lib/rt.jar ``` -------------------------------- ### Implement compiled BeanShell commands Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Commands can be implemented as Java classes with static invoke methods. ```java /** Implement dir() command. */ public static void invoke( Interpreter env, CallStack callstack ) { String dir = "."; invoke( env, callstack, dir ); } /** Implement dir( String directory ) command. */ public static void invoke( Interpreter env, CallStack callstack, String dir ) { ... } ``` -------------------------------- ### Run BshDoc from the command line Source: https://github.com/beanshell/beanshell/wiki/BshDoc Execute the bshdoc.bsh script using the BeanShell interpreter, passing the target script files as arguments and redirecting output to an XML file. ```bash java bsh.Interpreter bshdoc.bsh myfile.bsh [ myfile2.bsh ] [ ... ] > output.xml ``` -------------------------------- ### mv(String fromFile, String toFile) Source: https://github.com/beanshell/beanshell/wiki/Commands Renames or moves a file. ```APIDOC ## mv(String fromFile, String toFile) ### Description Renames a file from the source path to the destination path, similar to the Unix mv command. ### Parameters - **fromFile** (String) - Required - The current file path. - **toFile** (String) - Required - The target file path. ``` -------------------------------- ### browseClass Source: https://github.com/beanshell/beanshell/wiki/Commands Opens the class browser to view the specified class. ```APIDOC ## void browseClass( String | Object | Class ) ### Description Open the class browser to view the specified class. If the argument is a string it is considered to be a class name. If the argument is an object, the class of the object is used. ``` -------------------------------- ### Interpreter.source() Source: https://github.com/beanshell/beanshell/wiki/Embedding-BeanShell-in-Your-Application Reads and executes a BeanShell script from an external file. ```APIDOC ## Interpreter.source(String filename) ### Description Reads a script from an external file and evaluates it. ### Method public Object source(String filename) throws FileNotFoundException, IOException, EvalError ### Parameters - **filename** (String) - Required - The path to the script file. ``` -------------------------------- ### Inspect 'this' type references Source: https://github.com/beanshell/beanshell/wiki/Scope-Modifiers Demonstrates printing 'this' and 'super' references to identify the current BeanShell object context. ```beanshell BeanShell 1.3 - by Pat Niemeyer (pat@pat.net) bsh % print( this ); 'this' reference (XThis) to Bsh object: global bsh % foo() { print(this); print(super); } bsh % foo(); 'this' reference (XThis) to Bsh object: foo 'this' reference (XThis) to Bsh object: global ``` -------------------------------- ### dirname(String pathname) Source: https://github.com/beanshell/beanshell/wiki/Commands Returns the directory portion of a given path based on the system default file separator. ```APIDOC ## dirname(String pathname) ### Description Return directory portion of path based on the system default file separator. ### Parameters - **pathname** (String) - Required - The path string to process. ``` -------------------------------- ### print(arg) Source: https://github.com/beanshell/beanshell/wiki/Commands Prints the string value of the argument. ```APIDOC ## print(arg) ### Description Prints the string value of the argument to the command line or System.out. If the argument is an array, it lists the contents recursively. ### Parameters - **arg** (Object) - Required - The object to print. ``` -------------------------------- ### Execute BeanShell in Apache Ant Source: https://github.com/beanshell/beanshell/wiki/BSF-Bean-Scripting-Framework Shows how to run BeanShell scripts in Apache Ant using the script task with either an external file or inline code. ```xml ``` -------------------------------- ### Search for a method by signature Source: https://github.com/beanshell/beanshell/wiki/Reflective-Style-Access Use getMethod() with an array of Classes to locate a specific method signature. ```java name="bar"; signature = new Class [] { Integer.TYPE, String.class }; // Look up a method named bar with arg types int and String bshMethod = this.namespace.getMethod( name, signature ); print("Found method: "+bshMethod); ``` -------------------------------- ### Extend an object namespace Source: https://github.com/beanshell/beanshell/wiki/Commands Demonstrates how to create a child object that inherits variables from a parent object. ```beanshell foo=object(); bar=extend(foo); is equivalent to: foo() { bar() { return this; } } foo=foo(); bar=foo.bar(); and also: oo=object(); ar=object(); ar.namespace.bind( foo.namespace ); ``` -------------------------------- ### which Source: https://github.com/beanshell/beanshell/wiki/Commands Determines the source of a class file using classpath mapping. ```APIDOC ## which( classIdentifier | string | class ) ### Description Maps the classpath to determine the source of the specified class file, similar to the Unix 'which' command. ``` -------------------------------- ### cp Source: https://github.com/beanshell/beanshell/wiki/Commands Copies a file from one location to another. ```APIDOC ## cp( String fromFile, String toFile ) ### Description Copy a file (like Unix cp). ``` -------------------------------- ### Invoke a Method Source: https://github.com/beanshell/beanshell/wiki/Scripted-methods Call a defined method using standard syntax. ```java sum = addTwoNumbers( 5, 7 ); ``` -------------------------------- ### Verify Test Logic with Flags Source: https://github.com/beanshell/beanshell/blob/master/src/test/resources/README.txt Use the flag() counter to track execution flow and verify conditions within a test script. ```beanshell // Verify that 'if' works if ( true ) flag(); assert( flag() == 1 ); // Note: flag() is now 2 ``` -------------------------------- ### Enable automatic class importing Source: https://github.com/beanshell/beanshell/wiki/Class-Loading-and-Class-Path-Management Trigger automatic mapping of the classpath to allow importing classes without explicit statements. ```java import *; ``` -------------------------------- ### this.namespace.getMethod(String name, Class[] signature) Source: https://github.com/beanshell/beanshell/wiki/Reflective-Style-Access Searches for a specific method signature within the current namespace. ```APIDOC ## this.namespace.getMethod(String name, Class[] signature) ### Description Locates a specific method definition based on its name and argument types. Returns a bsh.BshMethod object. ### Parameters - **name** (String) - Required - The name of the method. - **signature** (Class[]) - Required - An array of Class objects representing the argument types. ``` -------------------------------- ### getBshPrompt() Source: https://github.com/beanshell/beanshell/wiki/Commands Retrieves the current BeanShell prompt string. ```APIDOC ## getBshPrompt() ### Description Get the value to display for the bsh interactive prompt. Checks for the variable bsh.prompt, otherwise returns 'bsh % '. ``` -------------------------------- ### Import object instance methods and fields Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Uses the importObject command to bring methods and fields of a Java object instance into the current namespace. ```java Map map = new HashMap(); importObject( map ); put("foo", "bar"); print( get("foo") ); // "bar" ``` -------------------------------- ### addClassPath Source: https://github.com/beanshell/beanshell/wiki/Commands Adds the specified directory, JAR file, or URL to the class path. ```APIDOC ## addClassPath( String | URL ) ### Description Adds the specified directory or JAR file to the class path. ### Parameters - **path** (String | URL) - Required - The path to the directory, JAR file, or URL to add. ``` -------------------------------- ### Invoke methods by name using eval() Source: https://github.com/beanshell/beanshell/wiki/Reflective-Style-Access Construct method calls as strings to invoke them dynamically within the current scope. ```java // Declare methods foo() and bar( int, String ) foo() { ... } bar( int arg1, String arg2 ) { ... } // Invoke a no-args method foo() by its name using eval() name="foo"; // invoke foo() using eval() eval( name+"()"); // Invoke two arg method bar(arg1,arg2) by name using eval() name="bar"; arg1=5; arg2="stringy"; eval( name+"(arg1,arg2)"); ``` -------------------------------- ### Create Object Context Source: https://github.com/beanshell/beanshell/wiki/Commands Initializes an empty BeanShell object context for storing data items. ```java myStuff = object(); myStuff.foo = 42; myStuff.bar = "blah"; ``` -------------------------------- ### BeanShell local scope demonstration Source: https://github.com/beanshell/beanshell/wiki/Scripted-objects Shows how variables defined within a method are local to that method's scope in BeanShell. ```java // Define the foo() method: foo() { int bar = 42; print( bar ); } // Invoke the foo() method: foo(); // prints 42 print( bar ); // Error, bar is undefined here ``` -------------------------------- ### Optimize execution with scripted methods Source: https://github.com/beanshell/beanshell/wiki/Parser Define a method once to parse it into an AST, then invoke it repeatedly to avoid re-parsing overhead. ```java // From Java import bsh.Interpreter; i=new Interpreter(); // Declare method or source from file i.eval("foo( args ) { ... }"); i.eval("foo(args)"); // repeatedly invoke the method i.eval("foo(args)"); ... ``` -------------------------------- ### thinBorder Source: https://github.com/beanshell/beanshell/wiki/Commands Creates a one pixel wide bevel border for components. ```APIDOC ## thinBorder( Color lightColor, Color darkColor, boolean rollOver ) ### Description Creates a one pixel wide bevel border, typically used for buttons or other UI components. ### Parameters - **lightColor** (Color) - Optional - The highlight color for the border. - **darkColor** (Color) - Optional - The shadow color for the border. - **rollOver** (boolean) - Optional - Whether the border supports rollover effects. ``` -------------------------------- ### Testing and Unsetting Variables Source: https://github.com/beanshell/beanshell/wiki/Special-Variables-and-Values Use the 'void' keyword to check if a variable is undefined and the 'unset()' command to return a variable to an undefined state. ```java if ( foobar == void ) // undefined ``` ```java a == void; // true a=5; unset("a"); // note the quotes a == void; // true ``` -------------------------------- ### cat Source: https://github.com/beanshell/beanshell/wiki/Commands Prints the contents of a file, URL, or stream. ```APIDOC ## cat( String | URL | InputStream | Reader ) ### Description Print the contents of filename, url, or stream (like Unix cat). ``` -------------------------------- ### Execute loosely typed Java syntax Source: https://github.com/beanshell/beanshell/wiki/Basic-syntax Demonstrates dynamic typing where variables are used without explicit type declarations. ```java /* Loosely Typed Java syntax */ // Use a hashtable hashtable = new Hashtable(); date = new Date(); hashtable.put( "today", date ); // Print the current clock value print( System.currentTimeMillis() ); // Loop for (i=0; i<5; i++) print(i); // Pop up a frame with a button in it button = new JButton( "My Button" ); frame = new JFrame( "My Frame" ); frame.getContentPane().add( button, "Center" ); frame.pack(); frame.setVisible(true); ``` -------------------------------- ### load(String filename) Source: https://github.com/beanshell/beanshell/wiki/Commands Loads a serialized Java object from the specified file. ```APIDOC ## load(String filename) ### Description Loads a serialized Java object from the provided filename and returns the object. ### Parameters - **filename** (String) - Required - The path to the serialized file. ``` -------------------------------- ### Operator-assignment evaluation Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Demonstrates the fix for evaluation of operator-assignments with postfix in the RHS. ```java i=1; i+=i++; // should be 2 apparently i=1; i+=i++ + i++; // should be 4 apparently ``` -------------------------------- ### Define global invoke meta-method Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Use the invoke meta-method to handle calls to undefined methods. ```java invoke( String methodName, Object [] arguments ) { print("You invoked the method: "+ methodName ); } // invoke() will be called to handle noSuchMethod() noSuchMethod("foo"); ``` -------------------------------- ### setNameSpace Source: https://github.com/beanshell/beanshell/wiki/Commands Swaps the current namespace (context) of the interpreter. ```APIDOC ## setNameSpace ### Description Set the namespace (context) of the current scope. ### Signature - setNameSpace(ns) ``` -------------------------------- ### Customizing the Command Prompt Source: https://github.com/beanshell/beanshell/wiki/Special-Variables-and-Values Define the getBshPrompt() method to customize the interactive command line prompt string. ```java getBshPrompt() { return bsh.cwd + " % "; } ``` -------------------------------- ### Override the BeanShell prompt Source: https://github.com/beanshell/beanshell/wiki/Commands Shows how to customize the interactive prompt by defining a custom getBshPrompt method. ```beanshell String getBshPrompt() { return bsh.cwd + " % "; } ``` -------------------------------- ### cd Source: https://github.com/beanshell/beanshell/wiki/Commands Changes the current working directory. ```APIDOC ## void cd( String pathname ) ### Description Change working directory for dir(), etc. commands (like Unix cd). ``` -------------------------------- ### Adding to classpath Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Adding a JAR to the BeanShell classpath before importing commands. ```java addClassPath("mycommands.jar"); importCommands("/mypackage/commands"); ``` -------------------------------- ### Variable Scoping Behavior Source: https://github.com/beanshell/beanshell/blob/master/CHANGES.md Demonstrates how variable assignments now search up the parent chain for definitions. ```java incrementX() { x=x+1; } x=1; incrementX(); assert( x == 2 ); // true! setFlag() { flag=true; } setFlag(); assert( flag == true ); // true! ``` -------------------------------- ### getClassPath Source: https://github.com/beanshell/beanshell/wiki/Commands Retrieves the current classpath, including user paths, extended paths, and the bootstrap JAR file. ```APIDOC ## URL[] getClassPath() ### Description Get the current classpath including all user path, extended path, and the bootstrap JAR file if possible. ### Returns - **URL[]** - An array of URLs representing the current classpath. ``` -------------------------------- ### setClassPath(URL[]) Source: https://github.com/beanshell/beanshell/wiki/Class-Loading-and-Class-Path-Management Replaces the entire current classpath with a new array of directories and/or archives, triggering a reload of all classes. ```APIDOC ## setClassPath(URL[]) ### Description Change the entire classpath to the specified array of directories and/or archives. This causes all classes to be reloaded. ### Parameters - **classpath** (URL[]) - Required - An array of directories or archives to set as the new classpath. ``` -------------------------------- ### Interpreter.set() and Interpreter.get() Source: https://github.com/beanshell/beanshell/wiki/Embedding-BeanShell-in-Your-Application Methods to inject variables into the interpreter context or retrieve values from it, supporting complex variable expressions. ```APIDOC ## Interpreter.set(String name, Object value) ### Description Sets a variable in the interpreter context. ### Method public void set(String name, Object value) throws EvalError ## Interpreter.get(String name) ### Description Retrieves the value of a variable from the interpreter context. ### Method public Object get(String name) throws EvalError ## Interpreter.unset(String name) ### Description Returns a variable to the undefined state. ### Method public void unset(String name) ``` -------------------------------- ### Defining nested methods Source: https://github.com/beanshell/beanshell/wiki/Scripted-objects Shows the syntax for defining methods within other methods in BeanShell. ```java foo() { bar() { ... } } ``` -------------------------------- ### frame(component) Source: https://github.com/beanshell/beanshell/wiki/Commands Displays a component in a frame. ```APIDOC ## frame(component) ### Description Show component in a frame, centered and packed, handling disposal with the close button. Returns the frame object. ``` -------------------------------- ### Passing Class Arguments to Commands Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Shows various ways to pass class references to BeanShell commands, including direct class types, object instances, and string names. ```java javap( Date.class ); // use a class type directly javap( new Date() ); // uses class of object javap( "java.util.Date" ); // Uses string name of class javap( java.util.Date ); // Use plain class identifier ``` -------------------------------- ### importCommands Source: https://github.com/beanshell/beanshell/wiki/Commands Imports scripted or compiled BeanShell commands from a specified package or path in the classpath. ```APIDOC ## void importCommands(String path) ### Description Import scripted or compiled BeanShell commands in the following package in the classpath. You may use either "/" path or "." package notation. ### Parameters - **path** (String) - The resource path or package name to import. ``` -------------------------------- ### Import BeanShell Commands Source: https://github.com/beanshell/beanshell/wiki/Basic-syntax Imports custom or default BeanShell commands from the specified classpath location. ```java importCommands("/bsh/commands"); ``` -------------------------------- ### Create overloaded BeanShell commands Source: https://github.com/beanshell/beanshell/wiki/Adding-BeanShell-Commands Define multiple versions of a command method within the same script file. ```java // File: helloWorld.bsh helloWorld() { print("Hello World!"); } helloWorld( String msg ) { print("Hello World: "+msg); } ``` -------------------------------- ### bg Source: https://github.com/beanshell/beanshell/wiki/Commands Sources a command in its own thread in the caller's namespace. ```APIDOC ## Thread bg( String filename ) ### Description Runs the command in its own thread. Returns the Thread object control. ``` -------------------------------- ### OSX Executable Script Source: https://github.com/beanshell/beanshell/wiki/Executable-Script Configures the shebang line specifically for the Java home path on OSX. ```java #!/Library/Java/home/bin/java bsh.Interpreter print("foo"); ```