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


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


java.lang.reflect.Field的getType()方法用於獲取此Field對象表示的字段的聲明類型。此方法返回一個Class對象,該對象標識聲明的類型

用法:

public String getType()

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


返回值:此方法返回一個Class對象,該對象標識聲明的類型。

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

// Java program to demonstrate getType() 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 getType Method on User Object 
        // to get the Type of Marks field 
        Class value = field.getType(); 
  
        // print result 
        System.out.println("Type"
                           + " is " + value); 
  
        // Now Get the Fees field object 
        field = User.class.getField("Fees"); 
  
        // Apply getType Method on User Object 
        // to get the Type of Fees field 
        value = field.getType(); 
  
        // print result 
        System.out.println("Type"
                           + " is " + value); 
    } 
} 
  
// sample User class 
class User { 
  
    // static double values 
    public static double Marks = 34.13; 
    public static float Fees = 3413.99f; 
  
    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; 
    } 
}
輸出:
Type is double
Type is float

示例2:

// Java program to demonstrate getType() 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].getType()); 
        } 
    } 
}
輸出:
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month
Name of Field: class java.time.Month

參考文獻: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getType–



相關用法


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