- Java Reflection — Methods
- Obtaining Method Objects
- Method Parameters and Return Types
- Invoking Methods using Method Object
- Java getMethod()
- Syntax
- How getMethod() work in Java?
- Examples to Implement Java getMethod()
- Example #1
- Example #3
- Conclusion
- Recommended Articles
- Java.lang.Class.getMethod() Method
- Declaration
- Parameters
- Return Value
- Exception
- Example
Java Reflection — Methods
Using Java Reflection you can inspect the methods of classes and invoke them at runtime. This is done via the Java class java.lang.reflect.Method . This text will get into more detail about the Java Method object.
Obtaining Method Objects
The Method class is obtained from the Class object. Here is an example:
Class aClass = . //obtain class object Method[] methods = aClass.getMethods();
The Method[] array will have one Method instance for each public method declared in the class.
If you know the precise parameter types of the method you want to access, you can do so rather than obtain the array all methods. This example returns the public method named «doSomething», in the given class which takes a String as parameter:
Class aClass = . //obtain class object Method method = aClass.getMethod("doSomething", new Class[]);
If no method matches the given method name and arguments, in this case String.class , a NoSuchMethodException is thrown.
If the method you are trying to access takes no parameters, pass null as the parameter type array, like this:
Class aClass = . //obtain class object Method method = aClass.getMethod("doSomething", null);
Method Parameters and Return Types
You can read what parameters a given method takes like this:
Method method = . // obtain method - see above Class[] parameterTypes = method.getParameterTypes();
You can access the return type of a method like this:
Method method = . // obtain method - see above Class returnType = method.getReturnType();
Invoking Methods using Method Object
You can invoke a method like this:
//get method that takes a String as argument Method method = MyObject.class.getMethod("doSomething", String.class); Object returnValue = method.invoke(null, "parameter-value1");
The null parameter is the object you want to invoke the method on. If the method is static you supply null instead of an object instance. In this example, if doSomething(String.class) is not static, you need to supply a valid MyObject instance instead of null ;
The Method.invoke(Object target, Object . parameters) method takes an optional amount of parameters, but you must supply exactly one parameter per argument in the method you are invoking. In this case it was a method taking a String , so one String must be supplied.
Java getMethod()
Java getMethod() is a method in java.lang.Class.getMethod() that returns an instance of Method class in package java.lang.reflect that holds the reference of given public member function present in the given Class object reference to a class or interface. This method takes the name of the method required to be passed as its first parameter. The second parameter to be passed is an array of objects of Class that determine the formal parameter datatypes of the returned method or an empty array determining null as paramterTypes. The search algorithm used in this is the same as of private GetPublicMethods() method.
Web development, programming languages, Software testing & others
getMethod() throws 3 types of exceptions as given below:-
Syntax
Below is the signature of the getMethod of java.lang.Class
public Method getMethod(String name, Class. parameterTypes) throws NoSuchMethodException, SecurityException
- public: This keyword determines that the given method can be accessed from any class in the project.
- Return Type Method: This method returns an instance of Method class that refers to the required method whose name has been passed as arguments.
- Parameters:
- Name This parameter refers to the String representation of the name of the method present in the referencing class or interface object. If no such method is present in the class, NoSuchMethodException is raised. Otherwise, the algorithm runs, and the method is returned.
- parameterTypes: This refers to an array of Class-type objects that point to the data that the method in name parameter requires as arguments. The size of this array depends upon the arguments required by the specified method name. If the method requires no arguments, null is passed into this argument.
If we have a class Demo as given below:
Then call to getMethod would be like:
Demo demoObj= new Demo();// Object of Demo class Class cObj= demoObj.getClass() Class [] carr = new Class[1]; carr[0] = String.class;// class reference to java.lang.String class stored In the array of type Class Method mObj = cObj.getMethod("method1",carr);
How getMethod() work in Java?
getMethod() returns a Method instance to the specified method in the referencing class or interface object.
- It takes a name parameter of String data type that holds the name of the public method that needs to be found in the specified class or interface. It also takes an array of Class Objects that represent the types of arguments for the function we are looking for.
- JVM reads the two arguments and performs a searching algorithm the same as used in the privateGetPublicMethods() method in java.lang.Class and search if the public method with the specified name is present or not. If there is more than one method is present in class, then the once with a more specific return type is returned. Otherwise, the method is chosen arbitrarily.
In case it finds the method, it returns an instance of Method Class holding its reference.
If the specified method does not need any argument, then null is passed in place of parameterType. This helps in the case of method overloading, where we have more than one method with the same name but differ in number or datatypes of arguments.This method throws 3 types of exceptions:-
1. NoSuchMethodException: This type of exception is thrown when JVM is not able to find any method with the specified name in class or interface.
2. SecurityException: This type of exception is thrown when
- checkMemberAccess(this, Member.PUBLIC) is invoked, denying access to it.
- The caller class load is different from the loader of the ancestor of the current class; thus, SecurityManagers.checkPackageAccess() is invoked; thus, access to the package is denied.
3. NullPointerException: This is thrown if null is passed in place of methods name in the arguments.
Examples to Implement Java getMethod()
Below are the examples mentioned:
Example #1
In this example, we will show the output of a getMethod call to two methods of Office class, one that requires objects and the other does not need an argument.
//package Proc; import java.lang.reflect.*; class Office < public String OfficeLocation() < return location; >public String getEmpName(Integer eid) < return"Sergio"; >String location = "Bangalore"; > public class prac1 < public static void main(String[] args) < Office ofc = new Office(); Class cObj = ofc.getClass(); Class[] carr = new Class[1]; carr[0] = Integer.class; try < Method meth = cObj.getMethod("OfficeLocation", null); System.out.println("Method with specified name is = " + meth.toString()); >catch(NoSuchMethodException e) < System.out.println(e.toString()); >try < Method meth = cObj.getMethod("getEmpName", carr); System.out.println("Method with specified name is alignnone size-full wp-image-371327" svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20619%2089'%3E%3C/svg%3E" alt="Java getMethod() - 1" width="619" height="89" data-lazy-srcset="https://cdn.educba.com/academy/wp-content/uploads/2020/05/Java-getMethod-1.png 619w, https://cdn.educba.com/academy/wp-content/uploads/2020/05/Java-getMethod-1-300x43.png 300w" data-lazy-sizes="(max-width: 619px) 100vw, 619px" data-lazy-src="https://cdn.educba.com/academy/wp-content/uploads/2020/05/Java-getMethod-1.png" /> Example #2
In this example, we will see if JVM is able to find private methods is the class with the given name.
//package Proc; import java.lang.reflect.*; public class prac1 < public static void main(String[] args) < Office ofc = new Office(); Class cObj = ofc.getClass(); try < Method meth = cObj.getMethod("OfficeLocation", null); System.out.println("Method with specified name is = " + meth.toString()); >catch(NoSuchMethodException e) < System.out.println(e.toString()); >> > class Office < private String OfficeLocation() < return location; >public String getEmpName(Integer eid) < return "Sergio"; >String location = "Bangalore"; >

Example #3
In this example , we will see how different exceptions occur when a non-existing method is called, and null is passed in the method’s name.
//package Proc; import java.lang.reflect.*; class Office < public String OfficeLocation() < return location; >public String getEmpName(Integer eid) < return "Sergio"; >String location = "Bangalore"; > public class prac1 < public static void main(String[] args) < Office ofc = new Office(); Class cObj = ofc.getClass(); Class[] carr = new Class[1]; carr[0] = Integer.class; try < Method meth = cObj.getMethod("show", null); System.out.println("Method found " + meth.toString()); >catch(NoSuchMethodException e) < System.out.println(e.toString()); >try < Method meth = cObj.getMethod(null, carr); System.out.println("Method found" + meth.toString()); >catch(NoSuchMethodException e) < System.out.println(e.toString()); >catch(NullPointerException e) < System.out.println(e.toString()); >> >

Conclusion
Java.lang.getMethod() is a method used to search if a method with the given name and type of arguments is present in the class or not. It uses the same algorithm to find the method used in the privateGetPublicMethods() method. JVM search for the given public method and returns a Method instance; otherwise, NoSuchMethodException is raised.
Recommended Articles
This is a guide to Java getMethod(). Here we discuss an introduction to Java getMethod() with appropriate syntax, parameters, how does it work, and example. You can also go through our other related articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA Course Bundle - 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8
Java.lang.Class.getMethod() Method
The java.lang.Class.getMethod() returns a Method object that reflects the specified public member method of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired method.
The parameterTypes parameter is an array of Class objects that identify the method's formal parameter types, in declared order. If parameterTypes is null, it is treated as if it were an empty array. .
Declaration
Following is the declaration for java.lang.Class.getMethod() method
public Method getMethod(String name, Class. parameterTypes) throws NoSuchMethodException, SecurityException
Parameters
- name − This is the name of the method.
- parameterTypes − This is the list of parameters.
Return Value
This method returns the Method object that matches the specified name and parameterTypes.
Exception
- NoSuchMethodException − if a matching method is not found or if the name is or .
- NullPointerException − If name is null
- SecurityException − If a security manager, s, is present.
Example
The following example shows the usage of java.lang.Class.getMethod() method.
package com.tutorialspoint; import java.lang.reflect.*; public class ClassDemo < public static void main(String[] args) < ClassDemo cls = new ClassDemo(); Class c = cls.getClass(); try < // parameter type is null Method m = c.getMethod("show", null); System.out.println("method = " + m.toString()); >catch(NoSuchMethodException e) < System.out.println(e.toString()); >try < // method Long Class[] cArg = new Class[1]; cArg[0] = Long.class; Method lMethod = c.getMethod("showLong", cArg); System.out.println("method result notranslate">method = public java.lang.Integer com.tutorialspoint.ClassDemo.show() method = public void com.tutorialspoint.ClassDemo.showLong(java.lang.Long)