Javascript .apply() method equivalent in Java?

2019-02-14 13:21发布

问题:

I want to create a class in Java from a classname and an variable number of arguments (i.e. an Object[] args with variable length). Is there any way to achieve that?

Basically, the method would look like this in Javascript

function createClass(classname, args) {
    protoObject = Object.create(window[classname].prototype);
    return window[classname].apply(protoObject,args) || protoObject;
}
// I want to be able to do this:
var resultClass = createClass("someClass", someArrayOfArgs);

A simpler function to only call a function would look like

function callFunction(functionName, args) {
    return window[functionName].apply(null,args);
}

Thanks!


For clarification, this would be some example usage in Javascript:

function multiplyResult(var1,var2) { 
    return var1*var2;
}
var result = callFunction("multiplyResult", ["5", "2"]); // == 10

function multiplyObject(var1,var2) { 
    var result = var1 * var2;
    this.getResult = function() { return result }; 
}
var result = createClass("multiplyObject", ["5", "2"]).getResult(); // == 10

回答1:

It turns out that you can simply provide an Object[] to the invoke() function and that it will work exactly like .apply() in Javascript. Take the following function.

public int multiply(int int1, int int2) {
    return int1*int2;
}

From the same class, it works to call the function like

Object result = this.getClass().getDeclaredMethod("multiply",classes).invoke(this,ints);

with classes and ints being something like

Class[] classes = new Class[] {int.class, int.class};
Object[] ints = new Object[] {2,3};    


回答2:

I think you need something like this. You can use reflection the invoke a method.

      Method method =  Class.forName("className").getMethod("methodName", Parameter1.class, Parameter2.class);

      MethodReturnType result= (MethodReturnType) method.invoke(Class.forName("className"), new Object[]{parameter1, parameter2});


回答3:

It goes like this:

 Class.forName("foo").clazz.getConstructor(<classes>).newInstance(... parameters)

but unlike javascript you have strong typing and have to say which constructor you like to have.