[英]How to convert primitive long datatype to Class type for Class.getMethod(methodName, Class…);
我如何传递类型为long的数据类型作为接受任意param类的方法的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和字符串变量。
public Method getMethod(String name,
Class<?>... parameterTypes)
throws NoSuchMethodException,
SecurityException
Java将long
和Long
视为两种不同的类型。 前者是原始类型,而后者是引用类型。 您需要前者的Class
对象。
您可以通过执行long.class
来获得long
类。 实际上,通过执行ClassName.class
可以获取任何类的Class
对象。
因此,您的代码可以这样重写:
Class<fun> clazz = fun.class;
Method method = clazz.getMethod("getBox",long.class, String.class);
您可以将primitive.class
用于原语-在您的示例中:
Method method = clazz.getMethod("getBox", long.class, String.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.