How to find the return type of a method in JAVA?

Can anyone help me find the return type of the method in JAVA. I have tried this. But unfortunately, this will not work. Please guide me.

Method testMethod = master.getClass().getMethod("getCnt"); if(!"int".equals(testMethod.getReturnType())) { System.out.println("not int ::" + testMethod.getReturnType()); } 

Exit:

not int :: int

+7
source share
7 answers

The getReturnType() method returns Class

You can try:

 if (testMethod.getReturnType().equals(Integer.TYPE)){ .....; } 
+10
source
 if(!int.class == testMethod.getReturnType()) { System.out.println("not int ::"+testMethod.getReturnType()); } 
+4
source

The return type is Class<?> ... to get a row try:

  if(!"int".equals(testMethod.getReturnType().getName())) { System.out.println("not int ::"+testMethod.getReturnType()); } 
+1
source

getReturnType() returns a class object and you compare it to a string. You can try

 if(!"int".equals(testMethod.getReturnType().getName() )) 
+1
source

The getReturnType method returns a Class<?> Object not a String , which you compare with it. A Class<?> Object will never be equal to a String object.

To compare them you should use

!"int".equals(testMethod.getReturnType().toString())

+1
source

getretunType () returns a Class<T> . You can check that it is equal to type Integer

 if (testMethod.getReturnType().equals(Integer.TYPE)) { out.println("got int"); } 
+1
source

getReturnType() returns a Class<?> , not a String , so your comparison is incorrect.

Or

Integer.TYPE.equals (testMethod.getReturnType ())

or

int.class.equals (testMethod.getReturnType ())

+1
source

All Articles