Field getGenericType() method in Java with Examples
Last Updated :
30 May, 2022
The getGenericType() method of java.lang.reflect.Field used to return a Type object representing the declared type of this Field object. The returned type object can be one of the implementations of Type’s subinterfaces: GenericArrayType, ParameterizedType, WildcardType, TypeVariable, Class. If the Type of Field object is a parameterized type, the returned Type object must accurately reflect the actual type parameters used in the source code and if the type of the underlying field is a type variable or a parameterized type, it is created. Otherwise, it is resolved. Syntax:
public Type getGenericType()
Parameters: This method accepts nothing. Return: This method returns a Type object that represents the declared type for the field represented by this Field object. Exception: This method returns the following Exceptions:
- GenericSignatureFormatError: if the generic field signature does not conform to the format specified in The Javaâ„¢ Virtual Machine Specification.
- TypeNotPresentException: if the generic type signature of the underlying field refers to a non-existent type declaration.
- MalformedParameterizedTypeException: if the generic signature of the underlying field refers to a parameterized type that cannot be instantiated for any reason.
Below programs illustrate getGenericType() method: Program 1:
Java
import java.lang.reflect.Field;
import java.lang.reflect.Type;
public class GFG {
private static int number;
public static void main(String[] args)
throws NoSuchFieldException
{
Field field
= GFG. class
.getDeclaredField("number");
Type type = field.getGenericType();
System.out.println(
"Type class : "
+ type.getClass());
System.out.println(
"Type name: "
+ type.getTypeName());
}
}
|
Output:
Type class: class java.lang.Class
Type name: int
Program 2:
Java
import java.lang.reflect.Field;
import java.lang.reflect.Type;
public class GFG {
final static String value = "Geeks";
public static void main(String[] args)
throws NoSuchFieldException
{
Field field
= GFG. class
.getDeclaredField("value");
Type type = field.getGenericType();
System.out.println(
"Type class : "
+ type.getClass());
System.out.println(
"Type name: "
+ type.getTypeName());
}
}
|
Output:
Type class: class java.lang.Class
Type name: java.lang.String
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getGenericType–
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...