Field getShort() method in Java with Examples
The getShort() method of java.lang.reflect.Field used to get the value of short which has to be static or instance field type. This method also used to get the value of another primitive type convertible to type short via a widening conversion. When a class contains a static or instance short field and we want to get the value of that field then we can use this method to return the value of Field.
Syntax:
public short getShort(Object obj)
throws IllegalArgumentException,
IllegalAccessException
Parameters: This method accepts a single parameter obj which is the object to extract the short value from.
Return value: This method returns the value of field converted to type short.
Exception: This method throws following Exception:
- IllegalAccessException: if Field object is enforcing Java language access control and the underlying field is inaccessible.
- IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field or if the field value cannot be converted to the type short by a widening conversion.
- NullPointerException: if the specified object is null and the field is an instance field.
- ExceptionInInitializerError: if the initialization provoked by this method fails.
Below programs illustrate getShort() method:
Program 1:
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
User user = new User();
Field field
= User. class .getField( "Marks" );
short value = field.getShort(user);
System.out.println( "Value of short Field"
+ " Marks is " + value);
}
}
class User {
public static short Marks = 34 ;
public static String name = "Aman" ;
public static short getMarks()
{
return Marks;
}
public static void setMarks( short marks)
{
Marks = marks;
}
public static String getName()
{
return name;
}
public static void setName(String name)
{
User.name = name;
}
}
|
Output:
Value of short Field Marks is 34
Program 2:
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
SmallerNumbers smallNo
= new SmallerNumbers();
Field field = SmallerNumbers. class
.getField( "value" );
short value = field.getShort(smallNo);
System.out.println( "Value: " + value);
}
static class SmallerNumbers {
public static short value = 999 ;
public static short getValue()
{
return value;
}
public static void setValue( short value)
{
SmallerNumbers.value = value;
}
}
}
|
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getShort-java.lang.Object-
Last Updated :
26 Aug, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...