简体   繁体   中英

Explanation and proper format of "parameterTypes" in "java.lang.Class.getMethod()" method

I have the following code -

MyInterface.java -

    default int getNumber() {
        System.out.print("Number: ");
        return in.nextInt();
    }

    default void displayNumber(int num) {
        System.out.println("Number: " + num);
    }

Main.java -

        int num;

        MyInterface obj = new MyInterface() {
        };

        num = (int) obj.getClass().getMethod("getNumber").invoke(obj);
        obj.getClass().getMethod("displayNumber", parameterType).invoke(obj);

I have left out the exceptions for clarity purpose

Here I have created the interface - MyInterface with two methods -

One method reads a number and returns it.

The other method takes a number as parameter and prints it.

In Main method I have created an inner class to implement the interface

Now using reflection and getMethod() I am able to successfully call the first method to read a number.

But I don't know the proper format to pass an argument using getMethod() and hence I am unable to successfully call the second method .

Here, what should be in place of parameterType ?

In Java Reflection, we represent types with Class objects. For any primitive, this can be obtained with the .TYPE value from any primitive wrapper class. In your instance, it looks like this would be Integer.TYPE (this would be the value for parameterType ).

Note also when you actually invoke displayNumber you will need to supply some actual value for your argument. For example, to represent the method invocation displayNumber(5) , you would have to make the last line the following:

obj.getClass().getMethod("displayNumber", Integer.TYPE).invoke(obj, new Integer(5));

As you can see, I am being careful with not assuming that primitive 5 is being autoboxed, as we tend to use Object as the static type frequently in Java reflection.

While ajc2000's answer is correct, I'd like to point out that the .class syntax would also work:

Retrieving Class Objects

If the type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

That is, the following would also work:

obj.getClass().getMethod("displayNumber", int.class).invoke(obj, 5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM