我有这段代码可以从动态类中获取 setter 方法。但参数可以是 java.lang.String 或 java.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获取完整示例。
编辑 现在再次阅读您的问题,我不确定上面的答案是否是您想要的。
您的意思是您的代码中有来自映射的参数并且您想通过反射调用正确的方法吗?是带有 Long
的还是 String
的?如果是这样,这里有一个例子:
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/