Java class fields, object use in Beanshell

▼魔方 西西 提交于 2019-12-23 16:59:46

问题


I am using Java with JSF and Beanshell script. I want to use fields and object of java class in beanshell. I have tried my best to get help from google but couldn't find any helpful information. For example

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import bsh.EvalError;
import bsh.Interpreter;

public class C {

static Map<String,Object> map = new HashMap<String,Object>();
static List<String> list = new ArrayList<String>();
static Map<String,Integer> integerMap = new HashMap<String,Integer>();

public static void main(String[] arg) throws EvalError{
    list.add("Hello");
    list.add("World");
    Interpreter i = new Interpreter();  // Construct an interpreter
    map.put("stringList", list);//in java
    i.eval("map.put(\"stringList\", list)");// gives error
    List list = (List) map.get("stringList");
    for(String str:(List<String>)list){
        System.out.println(str);
    }
  }
}

I want to perform all the operation which is available for collection in java to same object in beanshell.

Jmeter provide such facilities where user can update the variable in beanshell and based on the details given on link, it seems Jmeter is using string map and I want to do same things but it is with objects.

I would appreciate your inputs, if any technology in or framework which can be used to achieve my requirement would be good either java, beanshell, JSF or other available option in java.


回答1:


In JMeter's Beanshell or better JSR223 Sampler (Java language) you can put objects in JMeter variables as put:

JMeterVariables vars = JMeterContextService.getContext().getVariables();
vars.putObject("stringList", stringList);

and get:

vars.getObject("stringList");

In Java general case you need to add variable to Beanshell Interpreter with set method:

    list.add("Hello");
    list.add("World");
    Interpreter i = new Interpreter();  // Construct an interpreter

    map.put("stringList", list);//in java
    try {
        i.set("map", map); 
        i.set("list", list); 
        System.out.println(i.eval("map.put(\"stringList\", list)"));
    } catch (EvalError e1) {
        e1.printStackTrace();
    }


来源:https://stackoverflow.com/questions/46257426/java-class-fields-object-use-in-beanshell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!