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

标签 java reflection

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

相关文章:

java - 透明.png背景

java - 我如何获得所有 Cayenne 管理的实体类的列表?

java - Field.getGenericType() 返回 java.lang.Class 的实例而不是 Type

java - 由另一个内部类扩展的内部类

java - 正则表达式替换 Windows 在文件名中不接受的字符

c# - 在运行时创建类型 "MyClass : OtherClass<MyClass> { }"?

go - 为什么 golang reflect.MakeSlice 返回不可寻址的值

c# - 如何重写查询表达式以用整数替换枚举?

C# 反射 StackTrace 获取值

java - 无法在 Java 中使用 Batik 编辑 SVG?