问题描述:

Could anyone help me find the return type of a method in JAVA. I tried this. But unfortunately it doesn't work. Please guide me.

 Method testMethod = master.getClass().getMethod("getCnt");

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

{

System.out.println("not int ::" + testMethod.getReturnType());

}

Output :

not int ::int

网友答案:

The method getReturnType() returns 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 a Class<?>... to get a string try:

  if(!"int".equals(testMethod.getReturnType().getName()))
   {
      System.out.println("not int ::"+testMethod.getReturnType());
   }
网友答案:

getReturnType() return a Class object, and you are comparing to a string. You can try

if(!"int".equals(testMethod.getReturnType().getName() ))
网友答案:

The getReturnType method returns a Class<?> object not a String one which you are comparing it with. A Class<?> object will never be equal to a String object.

In order to compare them you have to use

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

网友答案:

getretunType() returns Class<T>. You can test it for being equal to type of Integer

if (testMethod.getReturnType().equals(Integer.TYPE)) {
    out.println("got int");
}
网友答案:

getReturnType() returns Class<?> rather than a String, so your comparing is incorrect.

Either

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

Or

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

相关阅读:
Top