Enhanced for loop
BeanShell is a small, free, embeddable Java source interpreter with object scripting language features,
written in Java. BeanShell is a natural scripting language for Java.
This requires the library bsh-2.0b4.jar to be in classpath.
The following example shows enhanced for loop in beanshell script.
int [] array = new int [] { 1 , 2 , 3 } ;
//Iterate int array
for ( i : array ) {
print ( i ) ;
}
//Iterate characters of string
for ( c : "BTC" ) {
print ( c ) ;
}
//Iterate student objects
for ( std : students ) {
print ( std.name + " " + std.age ) ;
}
package com.bethecoder.tutorials.bean_shell.common;
public class Student {
private String name;
private int age;
private String hobby;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public boolean isKid () {
return age < 5 ;
}
public String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + "]" ;
}
}
package com.bethecoder.tutorials.bean_shell;
import java.io.InputStreamReader;
import java.util.Arrays;
import bsh.EvalError;
import bsh.Interpreter;
import com.bethecoder.tutorials.bean_shell.common.Student;
public class EnhancedForLoopTest {
/**
* @param args
* @throws EvalError
*/
public static void main ( String [] args ) throws EvalError {
Student student = new Student ( "Sriram" , 2 , "Chess" ) ;
Student student2 = new Student ( "Sudhakar" , 29 , "Painting" ) ;
Student student3 = new Student ( "Charan" , 18 , "Reading books" ) ;
Interpreter interpreter = new Interpreter () ;
interpreter.set ( "students" , Arrays.asList ( student, student2, student3 )) ;
InputStreamReader reader = new InputStreamReader (
EnhancedForLoopTest. class .getClassLoader ()
.getResourceAsStream ( "enhanced_for_loop.bsh" )) ;
interpreter.eval ( reader ) ;
}
}
It gives the following output,
1
2
3
B
T
C
Sriram 2
Sudhakar 29
Charan 18