Get the declared method by name and parameter type in Java

Java 8Object Oriented ProgrammingProgramming

The declared method can be obtained by name and parameter type by using the java.lang.Class.getDeclaredMethod() method. This method takes two parameters i.e. the name of the method and the parameter array of the method.

The getDeclaredMethod() method returns a Method object for the method of the class that matches the name of the method and the parameter array that are the parameters.

A program that gets the declared method by name and parameter type using the getDeclaredMethod() method is given as follows −

Example

 Live Demo

package Test;
import java.lang.reflect.*;
public class Demo {
   public String str;
   private Integer func1() {
      return 1;
   }
   public void func2(String str) {
      this.str = "Stars";
   }
   public static void main(String[] args) {
      Demo obj = new Demo();
      Class c = obj.getClass();
      try {
         Method m1 = c.getDeclaredMethod("func1", null);
         System.out.println("The method is: " + m1.toString());
         Class[] argument = new Class[1];
         argument[0] = String.class;
         Method m2 = c.getDeclaredMethod("func2", argument);
         System.out.println("The method is: " + m2.toString());
      }
      catch(NoSuchMethodException e){
         System.out.println(e.toString());
      }
   }
}

Output

The method is: private java.lang.Integer Test.Demo.func1()
The method is: public void Test.Demo.func2(java.lang.String)

Now let us understand the above program.

In the class Demo, the two methods are func1() and func2(). A code snippet which demonstrates this is as follows −

public String str;
private Integer func1() {
   return 1;
}
public void func2(String str) {
   this.str = "Stars";
}

In the method main(), an object obj is created of class Demo. Then getClass() is used to get the class of obj in c. Finally, the getDeclaredMethod() method is used to get the methods func1() and func2() and they are displayed. A code snippet which demonstrates this is as follows −

Demo obj = new Demo();
Class c = obj.getClass();
try {
   Method m1 = c.getDeclaredMethod("func1", null);
   System.out.println("The method is: " + m1.toString());
   Class[] argument = new Class[1];
   argument[0] = String.class;
   Method m2 = c.getDeclaredMethod("func2", argument);
   System.out.println("The method is: " + m2.toString());
}
raja
Published on 09-Jan-2019 15:02:40
Advertisements