Java Field getLong()方法及示例

来源:这里教程网 时间:2026-02-17 20:50:41 作者:

Java Field getLong()方法及示例

java.lang.reflect.FieldgetLong() 方法用于获取必须是静态或实例字段类型的long值。这个方法也用来获取另一个原始类型的值,该类型可以通过拓扑转换为long类型。当一个类包含一个静态或实例长字段,并且我们想获得该字段的值时,我们可以使用这个方法来返回Field的值。

语法

public long getLong(Object obj)             throws IllegalArgumentException,                    IllegalAccessException

参数: 该方法接受一个单参数 obj ,它是要提取long值的对象。

返回值: 该方法返回转换为long类型的字段的值。

异常: 该方法抛出以下异常。

    IllegalAccessException: 如果字段对象正在执行Java语言的访问控制,并且底层字段是不可访问的。IllegalArgumentException: 如果指定的对象不是声明底层字段的类或接口的实例,或者如果字段值不能通过加宽转换转换为long类型。NullPointerException: 如果指定的对象是空的,并且该字段是一个实例字段。ExceptionInitializerError: 如果该方法引发的初始化失败。

以下程序说明了getLong()方法:

程序1 :

// Java program to demonstrate getLong() method  import java.lang.reflect.Field;  public class GFG {      public static void main(String[] args)        throws Exception    {          // Create the User class object        User user = new User();          // Get the marks field object        Field field            = User.class.getField("HighScore");          // Apply getLong Method on User Object        // to get the value of HighScore field        long value = field.getLong(user);          // print result        System.out.println("Value of long Field"                           + " HighScore is " + value);    }}  // sample User classclass User {      // static long values    public static long HighScore = 341313432299133L;    public static String name = "Aman";      public static long getHighScore()    {        return HighScore;    }      public static void setHighScore(long HighScore)    {        User.HighScore = HighScore;    }      public static String getName()    {        return name;    }      public static void setName(String name)    {        User.name = name;    }}

输出:

Value of long Field HighScore is 341313432299133

程序2

// Java program to demonstrate getLong() method  import java.lang.reflect.Field;  public class GFG {      public static void main(String[] args)        throws Exception    {          // Create the Numbers class object        Numbers numbers = new Numbers();          // Get the value field object        Field field            = Numbers.class.getField("value");          // Apply getLong Method on field Object        // to get the value of value field        long value = field.getLong(numbers);          // print result        System.out.println("Value: " + value);    }      // Numbers class    static class Numbers {          // long field        public static long value = 9999994567L;          // getter and setter methods        public static long getValue()        {            return value;        }          public static void setValue(long value)        {            Numbers.value = value;        }    }}

输出:

Value: 9999994567

参考文献 : https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getLong-java.lang.Object-

相关推荐