Java Field toString()方法及示例
java.lang.reflect.Field 的 toString() 方法用于获取描述此Field的字符串。返回的字符串的格式是该字段的访问修饰符(如果有的话),后面是字段类型,后面是空格,后面是声明该字段的类的全称,后面是句号,后面是该字段的名称。
比如说 。
public static final Month java.time.Month.APRIL
这些修饰符是按照《Java语言规范》规定的规范顺序放置的。首先是public、protected或private,然后是其他修饰符,顺序如下:static、final、transient、volatile。
语法
public String toString()
参数: 此方法不接受任何东西。
返回值: 该方法返回一个描述该字段的 字符串 。
下面的程序说明了toString()方法:
程序1 :
// Java program to illustrate toString() method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
// Get the array of field object
Field[] fields = User.class.getFields();
// loop
for (int i = 0; i < fields.length; i++) {
// get the string representation of each field
String field = fields[i].toString();
System.out.println("Field: " + field);
}
}
}
// sample User class
class 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;
}
}
输出:
Field: public static double User.Marks
Field: public static float User.Fees
Field: public static java.lang.String User.name
程序2
// Java program to illustrate toString() 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("toString of Field:\n"
+ fields[i].toString());
}
}
}
输出:
toString of Field:
public static final java.time.Month java.time.Month.January
toString of Field:
public static final java.time.Month java.time.Month.FebRUARY
toString of Field:
public static final java.time.Month java.time.Month。MARCH
toString of Field:
public static final java.time.Month java.time.Month.APRIL
toString of Field:
public static final java.time.Month java.time.Month.May
toString of Field:
public static final java.time.Month java.time.Month.6月
toString of Field:
public static final java.time.Month java.time.Month.July
toString of Field:
public static final java.time.Month java.time.Month.AUGUST
toString of Field:
public static final java.time.Month java.time.Month.SEPTEMBER
toString of Field:
public static final java.time.Month java.time.Month.OctOBER
toString of Field:
public static final java.time.Month java.time.Month.NOVEMBER
toString of Field:
public static final java.time.Month java.time.Month.DecEMBER
引用 :https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#toString-