Get Returned Type – Java

In general when you are developing software you need to have a good idea of the different classes that are needed and for each class the members and methods. Under some special circumstances you might run into classes that are not documented and you need to get some information as to the returned values. Please bear with me attempting to provide a good example. In practice most of the time (do not generalize) you will have such information displayed in your IDE or in documentation provided by the vendor.

I recall many years ago trying to process some images not knowing the actual format. I had to spend time figuring out the structure of the files. In general you get information from the vendor regarding their software. One way or the other, the Java programming language provides a class that allows at runtime get the names of methods and the returned types of a class.

This post is specific to the Java programming language so we will use it. The code was developed and executed on a Windows 10 machine. I used the VSCode IDE.

The java.lang.reflectMethod Class allows you to get information of a method on a class or interface. This class provides access all the methods of a class.

All methods in a class have a return type. The getReturnType() method of Method class returns a Class object that represent the return type.

main <<< methods.length: 11
main <<<       name: toString
main <<< returnType: java.lang.String
main <<<       name: setVal
main <<< returnType: void
main <<<       name: getVal
main <<< returnType: int
main <<<       name: wait
main <<< returnType: void
main <<<       name: wait
main <<< returnType: void
main <<<       name: wait
main <<< returnType: void
main <<<       name: equals
main <<< returnType: boolean
main <<<       name: hashCode
main <<< returnType: int
main <<<       name: getClass
main <<< returnType: java.lang.Class
main <<<       name: notify
main <<< returnType: void
main <<<       name: notifyAll
main <<< returnType: void
main <<< EXCEPTION Index 11 out of bounds for length 11

The output of our test scaffolding illustrates that a particular class (will see it in the source code) has a total of 11 methods. The program displays the name of the method followed by the type of object they return. The first method is toString() which as expected, should return an object of type java.lang.String which during development we abbreviate it to String.

The second method seems to be a setter. In general setter methods are of type void because they do not return a value. The third method getVal() is a getter so it should return a type different than void; and it does.

Note that the last line in the code appears to throw an exception which our program caught. The reason for it is to check that a section of code could throw an exception, and verify that the program would be able to catch it. I could have removed the cause of the exception, but decided to leave it enabled.

main <<< methods.length: 10
main <<<       name: main
main <<< returnType: void
main <<<       name: wait
main <<< returnType: void
main <<<       name: wait
main <<< returnType: void
main <<<       name: wait
main <<< returnType: void
main <<<       name: equals
main <<< returnType: boolean
main <<<       name: toString
main <<< returnType: java.lang.String
main <<<       name: hashCode
main <<< returnType: int
main <<<       name: getClass
main <<< returnType: java.lang.Class
main <<<       name: notify
main <<< returnType: void
main <<<       name: notifyAll
main <<< returnType: void
main <<< EXCEPTION Index 10 out of bounds for length 10

This is similar to what we saw in the previous run. It seems like we are looking at a different class because the number of methods, names and returned types differ.

/**
 * Definition for singly-linked list.
 * Class to get methods and returned types.
 */
class ListNode {

    // **** members ****
    int         val;
    ListNode    next;

    // **** constructors ****
    ListNode() {
    }

    ListNode(int val) {
        this.val = val; 
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    // **** getter and setters ****
    public void setVal(int val) {
        this.val = val;
    }

    public int getVal() {
        return this.val;
    }

    // **** added for testing (not required) ****
    @Override
    public String toString() {
        return "" + this.val;
    }
}

We have defined a class named ListNode which with some minor modifications was used in a previous post. The class has a couple of members and a set of six methods (at least the ones we have defined). The first pass of the program returned information about this class. We will shortly find out what we did for the second pass.

/**
 * Display the names of methods and returned types
 * for the specified class.
 */
public class Solution {


    /**
     * Test scaffolding.
     */
    public static void main(String[] args) {
        
        // **** might get an exception ****
        try {

            // **** create a class object ****
            // Class<?> classObject = ListNode.class;
            Class<?> classObject = Solution.class;

            // **** get a list of all methods in the class ****
            Method[] methods = classObject.getMethods();

            // **** display the number of methods in the class ****
            System.out.println("main <<< methods.length: " + methods.length);

            // **** iterate through the methods ****
            // for (Method method : methods) {
            for (int i = 0; i <= methods.length; i++) {

                // ???? ????
                Method method = methods[i];

                // **** display method name ****
                System.out.println("main <<<       name: " + method.getName());

                // **** get the return type ****
                Class<?> returnType = method.getReturnType();

                // **** display the return type ****
                System.out.println("main <<< returnType: " + returnType.getName());
            }

        } catch (Exception e) {
            System.out.println("main <<< EXCEPTION " + e.getMessage());
        }

    }

}

This is the test scaffolding for our program. The core of the main method is enclosed in a try-catch. The reason for it is that the methods we use may throw exceptions when used improperly. Since I just wanted to test out if the block was working I used a different for loop to get passed the number of methods so our code will throw an exception. You can remove the loop and uncomment the original loop and remove the assignment of the method variable from the methods array. That will eliminate the exception.

The first couple lines in the try-catch bock shows that on the first pass we used the ListNode class previously defined. Perhaps of more interest would be the second line (currently enabled) which allows us to check all the methods in the Solution class.

I guess if you are writing a Java compiler or lint utility these classes and methods would be more useful.

The entire code for this project can be found in my GitHub repository.

If you have comments or questions regarding this, or any other post in this blog, or if you would like for me to serve of assistance with any phase in the SDLC (Software Development Life Cycle) of a project associated with a product or service, please do not hesitate and leave me a note below. If you prefer, send me a private message using the following address:  john.canessa@gmail.com. I will reply as soon as possible.

Keep on reading and experimenting. It is the best way to learn, become proficient, refresh your knowledge and enhance your developer toolset!

One last thing, many thanks to all 1,702 subscribers to this blog!!!

Keep safe during the COVID-19 pandemic and help restart the world economy.

John

Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.