简体   繁体   中英

How to convert primitive long datatype to Class type for Class.getMethod(methodName, Class…);

How can i pass a datatype of type long as a param for method which is accepting arbitrary param Class...

I am actually trying to get the reflection of a method from the below class.

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

Trying to access this method using below Code.

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

Iam getting the below exception when i try accessing the method name for invoking.

java.lang.NoSuchMethodException:

How to pass a long and a string variable for parametertypes in the below method signature.

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

Java considers long and Long as two different types. The former is a primitive type while the latter is a reference type. You need the Class object of the former.

You can get the class of long by doing long.class . Actually, you can get the Class object of any class by doing ClassName.class .

Therefore, your code can be rewritten like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM