gpt4 book ai didi

java - 使用反射从动态方法获取参数类型

转载 作者:行者123 更新时间:2023-11-30 08:50:33 25 4
gpt4 key购买 nike

我有这段代码可以从动态类中获取 setter 方法。但参数可以是 java.lang.Stringjava.lang.Long。如何动态获取参数类型?

public Method getDynMethod(Class aClass, String methodName) {
Method m = null;
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class;
try {
m = aClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException nsme) {
nsme.printStackTrace();
}
return m;
}

这是调用它的代码

Class c = getDynClass(a.getAssetType().getDBTableName());
for (Long l : map.keySet()) {
AssetProperties ap = new AssetProperties();
ap.setAssetTypeProperties(em.find(AssetTypeProperty.class, l));
ap.setAssets(a);
ap.setValue(map.get(l));
a.getAssetProperties().add(ap);
String methodName = "set" + ap.getAssetTypeProperties().getDBColumn();
Method m = getDynMethod(c, methodName);
try {
String result = (String) m.invoke(c.newInstance(), ap.getValue());
System.out.println(result);
} catch (IllegalAccessException iae) {
iae.printStackTrace();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
} catch (InstantiationException ie) {
ie.printStackTrace();
}

}

我可以将另一个参数传递给该方法,但我仍然不知道参数类型是什么

最佳答案

您可以从method.getParameterTypes() 获取方法的参数类型;即:

public Class[] methodsParamsTypes(Method method) {
return method.getParameterTypes();
}

参见 here一个完整的例子。

编辑现在再次阅读您的问题我不确定上面的答案是否是您正在寻找的。

您的意思是您的代码中有来自 map 的参数,并且您想通过反射调用正确的方法吗?带有 LongString 的那个?如果是这样,这是一个例子:

public Method getDynMethod(Class aClass, String methodName, Object...params) {
Method m = null;
Class[] paramTypes = new Class[params.length];
for (int i = 0; i < paramTypes.length; i++) {
//note: if params[i] == null is not possible to retrieve the class type...
paramTypes[i] = params[i].getClass();
}
try {
m = aClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException nsme) {
nsme.printStackTrace();
}
return m;
}

在您的代码中,您可以这样调用它:

Method m = getDynMethod(c, methodName, ap.getValue());

关于java - 使用反射从动态方法获取参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30937796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com