Java Field getType()方法及示例

Java Field getType()方法及示例

java.lang.reflect.FieldgetType() 方法用于获取该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-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程