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
The getReturnType() method returns Class
getReturnType()
Class
You can try:
if (testMethod.getReturnType().equals(Integer.TYPE)){ .....; }
if(!int.class == testMethod.getReturnType()) { System.out.println("not int ::"+testMethod.getReturnType()); }
The return type is Class<?> ... to get a row try:
Class<?>
if(!"int".equals(testMethod.getReturnType().getName())) { System.out.println("not int ::"+testMethod.getReturnType()); }
getReturnType() returns a class object and you compare it to a string. You can try
if(!"int".equals(testMethod.getReturnType().getName() ))
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.
getReturnType
String
To compare them you should use
!"int".equals(testMethod.getReturnType().toString())
getretunType () returns a Class<T> . You can check that it is equal to type Integer
Class<T>
if (testMethod.getReturnType().equals(Integer.TYPE)) { out.println("got int"); }
getReturnType() returns a Class<?> , not a String , so your comparison is incorrect.
Or
Integer.TYPE.equals (testMethod.getReturnType ())
or
int.class.equals (testMethod.getReturnType ())