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?
Aucun commentaire:
Enregistrer un commentaire