Java – can I force the elimination of what rhinoceros calls overloading?
Perform the following tests:
public static class Scripted { public void setThing(List<?> list) { System.out.println("Set via list"); } public void setThing(Object[] array) { System.out.println("Set array"); } } @Test public void testScripting() throws Exception { ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js"); engine.getContext().setAttribute("s",new Scripted(),ScriptContext.ENGINE_SCOPE); engine.eval("s.thing = Array(1,2,3);"); }
With the Java 7 version released by rhino, if you run this, you will get an exception like this:
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: The choice of Java constructor setThing matching JavaScript argument types (object) is ambiguous; candidate constructors are: void setThing(java.util.List) void setThing(java.lang.Object[]) (<UnkNown source>#1) in <UnkNown source> at line number 1
First, the object [] overload exists because rhino in previous versions did not automatically convert arrays to lists, but converted them to object []
If this is a personal project, I will delete the object [] overload The problem is that this is a public API, and someone may call this method now I still want to upgrade to Java 7, but I want to avoid bothering JavaScript users or people who use the array version of the method
Is there any way to hide the object [] overloaded methods from rhino, while other methods can still call them?
Solution
Although it is not very elegant, there is a special method to call an overloaded Java method It is defined in the last section of the Java method overloading and liveconnect 3 specification Basically, you use square brackets for the entire signature, and use square brackets to display in the error message In your case, the following should work:
s["setThing(java.util.List)"](Array(1,3));
Unfortunately, we use Java util. Changes to the JavaScript array of list will destroy existing code Perhaps it's best to choose one, just in case there are multiple matching methods