如何将原始long数据类型转换为Class.getMethod的类类型(methodName,Class ...);

时间:2017-06-26 16:54:05

标签: java methods reflection

如何传递long类型的数据类型作为接受任意param类的方法的参数...

我实际上是想从下面的类中得到一个方法的反映。

 Class Fun(){public Object getBox(long boxId, String boxName){}}

尝试使用以下代码访问此方法。

Class clazz = new fun().getClass(); String str = "Welcome"; Method method = clazz.getMethod("getBox",new Long(22).getClass, str.getClass());

当我尝试访问方法名称以进行调用时,我得到以下异常。

java.lang.NoSuchMethodException:

如何在以下方法签名中为参数类型传递long和string变量。

public Method getMethod(String name,
               Class<?>... parameterTypes)
                 throws NoSuchMethodException,
                        SecurityException

2 个答案:

答案 0 :(得分:2)

Java将longLong视为两种不同的类型。前者是原始类型,后者是引用类型。您需要前者的Class对象。

您可以通过long获得long.class课程。实际上,您可以通过执行Class来获取任何类的ClassName.class对象。

因此,您的代码可以像这样重写:

Class<fun> clazz = fun.class;
Method method = clazz.getMethod("getBox",long.class, String.class);

答案 1 :(得分:0)

您可以使用primitive.class作为基元 - 在您的示例中:

Method method = clazz.getMethod("getBox", long.class, String.class);