Field getType() method in Java with Examples
Last Updated :
26 Aug, 2019
The getType() method of java.lang.reflect.Field used to get the declared type of the field represented by this Field object.This method returns a Class object that identifies the declared type
Syntax:
public String getType()
Parameters: This method accepts nothing.
Return value: This method returns a Class object that identifies the declared type.
Below programs illustrate getType() method:
Program 1:
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
Field field = User. class .getField( "Marks" );
Class value = field.getType();
System.out.println( "Type"
+ " is " + value);
field = User. class .getField( "Fees" );
value = field.getType();
System.out.println( "Type"
+ " is " + value);
}
}
class User {
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;
}
}
|
Output:
Type is double
Type is float
Program 2:
import java.lang.reflect.Field;
import java.time.Month;
public class GFG {
public static void main(String[] args)
throws Exception
{
Field[] fields = Month. class .getFields();
for ( int i = 0 ; i < fields.length; i++) {
System.out.println( "Name of Field: "
+ fields[i].getType());
}
}
}
|
Output:
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
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getType–
Share your thoughts in the comments
Please Login to comment...