Javascript .apply() method equivalent in Java?

拜拜、爱过 提交于 2019-11-30 22:08:27
Willem Mulder

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});

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!