Java Field getName()方法及示例

来源:这里教程网 时间:2026-02-17 20:50:41 作者:

Java Field getName()方法及示例

java.lang.reflect.FieldgetName() 方法用于获取该Field对象所代表的字段的名称。当一个类包含一个字段,我们想获得该字段的名称时,我们可以使用这个方法来返回字段的名称。

语法

public String getName()

参数: 该方法不接受任何东西。

返回值: 该方法返回一个 字符串 ,是基础成员的简单名称。

以下程序说明了getName()方法:

程序1 :

// Java program to demonstrate getName() method  import java.lang.reflect.Field;  public class GFG {      public static void main(String[] args)        throws Exception    {          // Get the marks field object        Field field = User.class.getField("Marks");          // Apply getName Method on User Object        // to get the name of Marks field        String value = field.getName();          // print result        System.out.println("Name"                           + " is " + value);          // Now Get the Fees field object        field = User.class.getField("Fees");          // Apply getName Method on User Object        // to get the name of Fees field        value = field.getName();          // print result        System.out.println("Name"                           + " is " + value);          // Now Get the name field object        field = User.class.getField("name");          // Apply getName Method on User Object        // to get the name of name field        value = field.getName();          // print result        System.out.println("Name"                           + " is " + value);    }}  // sample User classclass User {      // static double values    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;    }}

输出:

Name is MarksName is FeesName is name

程序2

// Java program to demonstrate getName() method  import java.lang.reflect.Field;import java.time.Month;  public class GFG {      public static void main(String[] args)        throws Exception    {          // Get all field objects of Month class        Field[] fields = Month.class.getFields();          for (int i = 0; i < fields.length; i++) {              // print name of Fields            System.out.println("Name of Field:"                               + fields[i].getName());        }    }}

输出:

Name of Field:JANUARYName of Field:FEBRUARYName of Field:MARCHName of Field:APRILName of Field:MAYName of Field:JUNEName of Field:JULYName of Field:AUGUSTName of Field:SEPTEMBERName of Field:OCTOBERName of Field:NOVEMBERName of Field:DECEMBER

参考文献 : https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getName-

相关推荐