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
Javascript's some() accepts a function pointer as an argument, which is not something that's natively supported in Java. But it should be fairly straight forward to emulate the functionality of some() in Java using a loop and and an interface for the callback functionality.
The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.
apply() The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object).
So to shortly recap: call is faster than apply because the input parameters are already formatted as necessary for the internal method.
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};
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With