我有一些代码可以从动态类中获取setter方法。但是参数可以是ajava.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();
}
}
我可以将另一个参数传递给方法,但是我仍然不知道参数类型是什么
您可以获取所有方法,并按名称进行过滤,如下所示:
public Method getDynMethod(Class aClass, String methodName) {
for (Method m : aClass.getMethods()) {
if (methodName.equals(m.getName())) {
Class<?>[] params = m.getParameterTypes();
if (params.length == 1
&& (params[0] == Long.class || params[0] == String.class)) {
return m;
}
}
}
return null;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句