Jericho
Jericho

Reputation: 10953

How to find return type of a method in Java?

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

Upvotes: 13

Views: 42947

Answers (8)

jupiter
jupiter

Reputation: 1

Use getretunType() to return a Class object, and then compare it with "int".equals(...)

Upvotes: -1

shuangwhywhy
shuangwhywhy

Reputation: 5625

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

Either

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

Or

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

Upvotes: 2

Gabriele Mariotti
Gabriele Mariotti

Reputation: 365068

The method getReturnType() returns Class

You can try:

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

Upvotes: 16

Seega
Seega

Reputation: 3400

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

Upvotes: 5

aviad
aviad

Reputation: 8278

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");
}

Upvotes: 1

Adam Arold
Adam Arold

Reputation: 30578

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())

Upvotes: 1

UmNyobe
UmNyobe

Reputation: 22920

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

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

Upvotes: 1

Esailija
Esailija

Reputation: 140234

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

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

Upvotes: 2

Related Questions