Field getName() method in Java with Examples
Last Updated :
26 Aug, 2019
The getName() method of java.lang.reflect.Field used to get the name of the field represented by this Field object. When a class contains a field and we want to get the name of that field then we can use this method to return the name of Field.
Syntax:
public String getName()
Parameters: This method accepts nothing.
Return value: This method returns a String which is the simple name of the underlying member.
Below programs illustrate getName() method:
Program 1:
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
Field field = User. class
.getField( "Marks" );
String value = field.getName();
System.out.println( "Name"
+ " is " + value);
field = User. class .getField( "Fees" );
value = field.getName();
System.out.println( "Name"
+ " is " + value);
field = User. class .getField( "name" );
value = field.getName();
System.out.println( "Name"
+ " is " + value);
}
}
class User {
public static double Marks = 34.13 ;
public static float Fees = 3413 .99f;
public static String name = "Aman" ;
public static double getMarks()
{
return Marks;
}
public static void setMarks( double marks)
{
Marks = marks;
}
public static float getFees()
{
return Fees;
}
public static void setFees( float fees)
{
Fees = fees;
}
public static String getName()
{
return name;
}
public static void setName(String name)
{
User.name = name;
}
}
|
Output:
Name is Marks
Name is Fees
Name is name
Program 2:
import java.lang.reflect.Field;
import java.time.Month;
public class GFG {
public static void main(String[] args)
throws Exception
{
Field[] fields = Month. class .getFields();
for ( int i = 0 ; i < fields.length; i++) {
System.out.println( "Name of Field:"
+ fields[i].getName());
}
}
}
|
Output:
Name of Field:JANUARY
Name of Field:FEBRUARY
Name of Field:MARCH
Name of Field:APRIL
Name of Field:MAY
Name of Field:JUNE
Name of Field:JULY
Name of Field:AUGUST
Name of Field:SEPTEMBER
Name of Field:OCTOBER
Name of Field:NOVEMBER
Name of Field:DECEMBER
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getName–
Share your thoughts in the comments
Please Login to comment...