Checking if the type of the returned method is a number?

As part autograder for a class that I teach, I wanted to check whether the student the method return type which has been studied numerically ( int, double, Integer, doubleetc.). I tried to do it as follows:

Method m = StudentClass.class.getDeclaredMethod(/* ... */);
return Number.class.isAssignableFrom(m.getReturnType());

This code will work correctly if the return type of the method is Integereither double, but not it intor double. It bothers me because it's legal to write

Number n = 137; // Assign an int to a Number

and

Number n = 1.608; // Assign a double to a Number

Why is the code that I wrote above correct if the method returns intor double? In addition to testing hard-coding, to see if the result is int, long, char, double, etc. What can I do to check whether the method returns the result of a numeric type?

Thank!

+3
2

, int, long, double , Number. , , - , , , , , , , .

, , http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html isNumber String.valueof. , , - /, , .

0

, . , , , ( Java ), .

public class Main {
    private static List<String> validTypes = new ArrayList<String>() {{
        add("int");
        add("Integer");
        add("double");
        add("Double");
        add("long");
        add("Long");
        add("float");
        add("Float");
    }};
    public static void main(String[] args) {
        Main main = new Main();
        for(Method m : main.getClass().getDeclaredMethods()){
            System.out.println(m.getName() + ": " + validTypes.contains(m.getReturnType().getSimpleName()));
        }
    }

    public static int mInt(){ return 1; }

    public static Integer mInteger(){ return 1; }

    public static double mDouble(){ return 1.0; }

    public static Double mDoubleD(){ return 1.0; }
}

main: false
mDoubleD: true
mInt: true
mInteger: true
mDouble: true
0

All Articles