2013-02-06 34 views
7

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

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

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

输出:

不是int ::诠释

回答

10

getReturnType()返回Class

的方法你可以试试:

if (testMethod.getReturnType().equals(Integer.TYPE)){ 
     .....; 
} 
+0

谢谢你的作品..... ..... – sunleo

+5

它通常是很好的约定来扭转等于避免潜在的NPE时,将实例等同于已知的常量(即'Integer.TYPE.equals(testmethod.getReturnType())') – indivisible

1

的返回类型是Class<?> ...得到一个字符串尝试:

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

谢谢它的作品。 ......... – sunleo

1

getReturnType()回报类对象,并且你正在比较一个字符串。 您可以尝试

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

downvoter评论请 – UmNyobe

+0

谢谢你的作品.......... – sunleo

1

getReturnType方法返回一个Class<?>对象不是String一个你与它比较。一个Class<?>对象将永远不会等于String对象。

为了比较它们,你必须使用

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

+0

谢谢你的作品.......... – sunleo

1

getretunType()返回Class<T>。您可以测试它等于整数类型

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

谢谢你的作品.. ........ – sunleo

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

谢谢你的作品.... ...... – sunleo

1

getReturnType()回报Class<?>而非String,所以你的比较不正确。

要么

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

或者

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

+0

谢谢你的作品.......... – sunleo

相关问题