普通のリフレクションを使ったやり方が分かりませんでした……。
jrunscript -q => Language ECMAScript 1.7 implemention "Rhino" Rhino 1.7 release 3 2012 05 18 System.out.println(System.getProperty("java.runtime.name")); => OpenJDK Runtime Environment System.out.println(System.getProperty("java.runtime.version")); => 1.7.0_25-b30
package foo; import java.io.File; public class Bar { private int[] intArray; private File[] fileArray; public File[] getFileArray() { return fileArray; } public void setFileArray(File[] fileArray) { this.fileArray = fileArray; } public int[] getIntArray() { return intArray; } public void setIntArray(int[] intArray) { this.intArray = intArray; } }
@Test public void test_set_primitiveArray() throws Exception { // bar.intArray に詰めたい foo.Bar bar = new Bar(); int[] arrayToSet = new int[] { 1, 2 }; // または // Object[] arrayToSet = new Integer[]{1, 2}; setArray(bar, "intArray", arrayToSet); assertThat( Arrays.toString(bar.getIntArray()), is("[1, 2]")); } @Test public void test_set_objectArray() throws Exception { // bar.fileArray に詰めたい foo.Bar bar = new Bar(); File[] arrayToSet = new File[] { new File("/home/user1"), new File("/home/user2") }; // または // Object[] arrayToSet = new File[] { new File("/home/user1"), new File("/home/user2") }; setArray(bar, "fileArray", arrayToSet); assertThat( Arrays.toString(bar.getFileArray()), is("[/home/user1, /home/user2]")); } private void setArray(Object obj, String fieldName, Object arrayToPut) throws ScriptException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.put("obj", obj); engine.put("arrayToPut", arrayToPut); String code = lines( " var tempArray = []; ", " for(var i=0; i<arrayToPut.length; i++){ ", " tempArray.push(arrayToPut[i]); ", " } ", " obj['" + fieldName + "'] = tempArray; " ); engine.eval(code); } private String lines(String... strings) { String text = ""; for (String it : strings) { text += it + "\n"; } return text; }