1

I'm looking through a list of methods and want to identify those that return a primitive (or a primitive wrapper class). Other than a big switch statement is there a simple way to do this?

Method[] methods = fooObj.getClass().getMethods();
for(int i = 0; i < methods.length; i++) {
    Method m = methods[i];
    Class c = m.getReturnType();
    if(c == void.class) {
        println("does not return anything.");
    }
    if( ??? ) {  // <--- what expression to use?
        println("a primitive, or primitive wrapper, is returned.");
    }
}
feybas
  • 163
  • 1
  • 1
  • 9
  • Maybe [this post](https://stackoverflow.com/questions/709961/determining-if-an-object-is-of-primitive-type) can help. – 0xCursor Jun 09 '18 at 01:22
  • @LAD sorry about that. I guess I should always look for the simplest solution. – feybas Jun 09 '18 at 01:25
  • So, it was helpful? – 0xCursor Jun 09 '18 at 01:26
  • @LAD of course. Given the funny way primitives are treated in java (everything is an object), I was focused on something much more creative and forgot to check the API. But, I'll take that solution! – feybas Jun 09 '18 at 01:52

2 Answers2

1

You can use commons-lang ClassUtils this way

Arrays
        .stream(Example.class.getDeclaredMethods())
        .filter(method -> ClassUtils.isPrimitiveOrWrapper(method.getReturnType()))
        .collect(Collectors.toList());
-1

In my suggestion for return type comparison - You can use if(returnType==Integer.TYPE)){...}

Sample Example:

import java.lang.reflect.Method;

class Example {

   public void m1() {
        System.out.println("No return");
   }

   public int m2() {
       return 1;
    }
}

public class MainApp {

public static void main(String[] args) {
        Example exp=new Example();
        Method[] declaredMethods = exp.getClass().getDeclaredMethods();
        for(Method m:declaredMethods) {
            Class<?> returnType = m.getReturnType();

            if(returnType==void.class) {
                System.out.println("No return");
            }

            //here is your solution 
            if(returnType==Integer.TYPE) {
                System.out.println("Integer return");
            }
        }
  }

}

Hope it is useful!!

  • This is arguably worse than the switch statement OP was trying to avoid . – Mad Physicist Jun 09 '18 at 04:52
  • Class has a method isPrimitive. Just use that. – Mad Physicist Jun 09 '18 at 04:53
  • Agree, i did not focus on switch par thought to focus on if condition for type comparison. for switch- Replace Conditional with Polymorphism might be usefule as we need to Create subclasses matching the branches of the conditional. In them, create a shared method and move code from the corresponding branch of the conditional to it. Then replace the conditional with the relevant method call. The result is that the proper implementation will be attained via polymorphism depending on the object class. – ayush agrahari Jun 09 '18 at 05:25