The getName() method of java.lang.reflect.Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects.
Syntax:
public String getName()
Return Value: It returns the name of the method, as String.
Example:
Method:public void getValue(){}
getName() returns: getValue
Explanation: The getName() function on object of above method returns name of method
which is getValue.
Method:public void paint(){}
getName() returns: paint
Below programs illustrates getName() method of Method class:
Example 1: Print name of all methods of Method Object.
import java.lang.reflect.Method;
public class GFG {
public static void main(String[] args)
{
try {
Class classobj = GFG. class ;
Method[] methods = classobj.getMethods();
for (Method method : methods) {
String MethodName = method.getName();
System.out.println( "Name of the method: "
+ MethodName);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static int setValue()
{
System.out.println( "setValue" );
return 24 ;
}
public String getValue()
{
System.out.println( "getValue" );
return "getValue" ;
}
public void setManyValues()
{
System.out.println( "setManyValues" );
}
}
|
Output:
Name of the method: main
Name of the method: getValue
Name of the method: setValue
Name of the method: setManyValues
Name of the method: wait
Name of the method: wait
Name of the method: wait
Name of the method: equals
Name of the method: toString
Name of the method: hashCode
Name of the method: getClass
Name of the method: notify
Name of the method: notifyAll
Example 2: Program to check whether class contains a certain specific method.
import java.lang.reflect.Method;
public class GFG {
public static void main(String[] args)
{
String checkMethod = "method1" ;
try {
Class classobj = democlass. class ;
Method[] methods = classobj.getMethods();
for (Method method : methods) {
String MethodName = method.getName();
if (MethodName.equals(checkMethod)) {
System.out.println( "Class Object Contains"
+ " Method whose name is "
+ MethodName);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
class democlass {
public int method1()
{
return 24 ;
}
public String method2()
{
return "Happy hours" ;
}
public void method3()
{
System.out.println( "Happy hours" );
}
}
|
Output:
Class Object Contains Method whose name is method1
Reference:
https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getName–
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Dec, 2018
Like Article
Save Article