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

Get parameter Type from dynamic method using reflection

我有这段代码可以从动态 class 中获取 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

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

你的意思是你的代码中有来自地图的参数,你想通过反射调用正确的方法吗?带有 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());

如果您想获取方法的参数类型,您应该调用名为

的方法

getParameterTypes() that returns an array of Class objects that are the parameter(s) expected.

查看此处了解更多信息: Method class Documentation

编辑:我忍了:- (

您可以获得所有方法,并按名称过滤,如下所示:

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