當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Field toGenericString()用法及代碼示例


java.lang.reflect.Field的toGenericString()方法用於返回表示此Field的字符串,包括其通用類型。字符串的格式是該字段的訪問修飾符(如果有),其後是通用字段類型,後跟一個空格,然後是聲明該字段的類的完全限定名稱,然後是一個句點,然後是字段名稱。

修飾符按照“ Java語言規範”中指定的規範順序放置。首先是公共的,受保護的或私有的,然後是其他修飾符,其順序如下:靜態,最終,瞬態,易失。

用法:


public String toGenericString()

參數:此方法接受不接受任何內容。

返回:此方法返回描述此Field的字符串,包括其通用類型。

以下示例程序旨在說明toGenericString()方法:
程序1:

// 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

程序2:

// 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://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#toGenericString-



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Field toGenericString() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。