Java中的字段 toGenericString() 方法及示例
Java.lang.reflect.Field的toGenericString()方法用于返回表示该字段的字符串,包括其泛型类型。字符串的格式是字段的访问修饰符(如果有),后跟通用字段类型,后跟一个空格,然后是声明该字段的类的完全限定名称,然后是句点,然后是字段的名称。
修饰符按“ Java语言规范”指定的规范顺序放置。这是公共的、受保护的或私有的,然后是其他修饰符,顺序如下:静态、最终、瞬态、易失。
句法:
public String toGenericString()
参数:此方法不接受任何内容。
Return :此方法返回描述此字段的字符串,包括其通用类型。
下面的程序说明了 toGenericString() 方法:
方案一:
// Java program to illustrate
// toGenericString() 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 the Month class
Field[] fields
= Month.class.getFields();
for (int i = 0; i < fields.length; i++) {
// print name of Fields
System.out.println(
"toGenericString of Field:\n"
+ fields[i].toGenericString());
}
}
}
toGenericString of Field:
public static final java.time.Month java.time.Month.JANUARY
toGenericString of Field:
public static final java.time.Month java.time.Month.FEBRUARY
toGenericString of Field:
public static final java.time.Month java.time.Month.MARCH
toGenericString of Field:
public static final java.time.Month java.time.Month.APRIL
toGenericString of Field:
public static final java.time.Month java.time.Month.MAY
toGenericString of Field:
public static final java.time.Month java.time.Month.JUNE
toGenericString of Field:
public static final java.time.Month java.time.Month.JULY
toGenericString of Field:
public static final java.time.Month java.time.Month.AUGUST
toGenericString of Field:
public static final java.time.Month java.time.Month.SEPTEMBER
toGenericString of Field:
public static final java.time.Month java.time.Month.OCTOBER
toGenericString of Field:
public static final java.time.Month java.time.Month.NOVEMBER
toGenericString of Field:
public static final java.time.Month java.time.Month.DECEMBER
方案二:
// Java program to illustrate
// toGenericString() method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
// create Numbers object
Numbers no = new Numbers();
// Get the value field object
Field field
= Numbers.class.getField("value");
// print value of isActive
System.out.println(
"toGenericString is\n"
+ field.toGenericString());
}
}
// sample Numbers class
class Numbers {
// static short value
public static short value = 13685;
}
toGenericString is
public static short Numbers.value
参考资料: https: Java