[英]Invoking method in a fly(dynamically) in Java
我是Java的新手。 我想創建一個方法,該方法將第一個參數作為Function,將第二個參數作為Objects List,如下所示:
public void dynamicMethodExecution(Somefunction someFunction, List<T> params) {
//Pass the params to the someFunction and execute the someFunction.
}
如果我將任何函數和參數列表傳遞給'dynamicMethodExecution',則它應通過傳遞參數來執行該函數。
此方法“ dynamicMethodExecution”應盡可能通用,即應采用任何功能並即時執行。
任何想法,我該怎么做?
如果您堅持使用內置的Function<T, F>
類,那么該類上的apply
方法就是這樣做的。 但是,正如我在評論中所說, Function
類僅表示一元函數,因此不能直接表示帶有零參數的函數或帶有多個參數的函數。
我終於做到了。 請分享您的看法。
public static void asyncMethodInvoke(Class<?> clazz, String methodName, Object[] args) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Class<?> params[] = new Class[args.length];
for (int i = 0; i < params.length; i++) {
if (args[i] instanceof Byte) {
params[i] = Byte.TYPE;
}
else if(args[i] instanceof Short) {
params[i] = Short.TYPE;
}
else if(args[i] instanceof Character) {
params[i] = Character.TYPE;
}
else if(args[i] instanceof Integer) {
params[i] = Integer.TYPE;
}
else if(args[i] instanceof Float) {
params[i] = Float.TYPE;
}
else if(args[i] instanceof Double) {
params[i] = Double.TYPE;
}
else if(args[i] instanceof Long) {
params[i] = Long.TYPE;
}
else if(args[i] instanceof Boolean) {
params[i] = Boolean.TYPE;
}
else {
params[i] = args[i].getClass();
}
}
Object _instance = clazz.newInstance();
Method method = clazz.getDeclaredMethod(methodName, params);
method.invoke(_instance, args);
}
catch (Exception e) {
System.out.println(e.getCause().getMessage());
}
}
}).start();
}
我正在使用線程異步運行方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.