Java中的Javascript .apply()方法等价吗? [英] Javascript .apply() method equivalent in Java?
问题描述
我想用类名和可变数量的参数(即具有可变长度的Object [] args)在Java中创建一个类。有没有办法实现这个目标?
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?
基本上,Javascript中的方法看起来像这样。
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);
}
谢谢!
为了澄清,这将是Javascript中的一些示例用法:
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
推荐答案
事实证明你可以只需向 invoke()
函数提供一个 Object []
,它的工作方式与。采用以下函数。
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);
类
和 ints
类似于
Class[] classes = new Class[] {int.class, int.class};
Object[] ints = new Object[] {2,3};
这篇关于Java中的Javascript .apply()方法等价吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!