如何在JAVA中找到Method的返回类型?

任何人都可以帮我找到JAVA中方法的返回类型。 我试过这个。 但不幸的是它不起作用。 请指导我。

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

输出:

不是int :: int

方法getReturnType()返回Class

你可以试试:

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

返回类型是Class …以获取字符串try:

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

getReturnType()返回一个Class对象,并且您正在与一个字符串进行比较。 你可以试试

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

getReturnType方法返回一个Class对象,而不是与之比较的String对象。 Class对象永远不会等于String对象。

为了比较它们你必须使用

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

getretunType()返回Class 。 您可以测试它是否等于Integer的类型

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

getReturnType()返回Class而不是String ,因此您的比较不正确。

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

要么

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