Is the Javascript.apply () method equivalent to Java?

I want to create a class in Java from a class name and a variable number of arguments (that is, arguments to Object [] with a variable length). Is there any way to achieve this?

Basically, the method will 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 just for calling the function will look like

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

Thanks!


For clarification, this will be an example of use 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 
+4
source share
3 answers

Turns out you can just provide Object [] with the invoke () function and that it will work just like .apply() in Javascript. Take the following function.

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

In the same class, it works to call a function like

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

with classes and ints , something like

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

Thank you all for your support!

+6
source

I think you need something like this. You can use reflection to call 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}); 
+1
source

This happens as follows:

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

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

+1
source

Source: https://habr.com/ru/post/1386516/


All Articles