当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Field setShort()用法及代码示例


java.lang.reflect.Field的setShort()方法用于将字段的值设置为指定对象的缩写。当您需要将对象的字段值设置为短时,可以使用此方法在对象上设置值。

用法:

public void setShort(Object obj, short s)
         throws IllegalArgumentException,
                IllegalAccessException

参数:此方法接受接受两个参数:


  • obj:是应该修改其字段的对象,并且
  • s:这是要修改的obj字段的新值。

返回:此方法不返回任何内容。

异常:此方法引发以下异常:

  • IllegalAccessException:如果此Field对象正在实施Java语言访问控制,并且基础字段是不可访问的或最终的。
  • IllegalArgumentException:如果指定的对象不是声明基础字段(或其子类或实现者)的类或接口的实例,或者展开的转换失败。
  • NullPoshorterException:如果指定的对象为null并且该字段是实例字段。
  • ExceptionInInitializerError:如果此方法引发的初始化失败。

以下示例程序旨在说明setShort()方法:
示例1:

// Java program to illustrate setShort() method 
  
import java.lang.reflect.Field; 
  
public class GFG { 
  
    public static void main(String[] args) 
        throws Exception 
    { 
  
        // create user object 
        Employee emp = new Employee(); 
  
        // print value of uniqueNo 
        System.out.println( 
            "Value of uniqueNo before "
            + "applying setShort is "
            + emp.uniqueNo); 
  
        // Get the field object 
        Field field 
            = Employee.class
                  .getField("uniqueNo"); 
  
        // Apply setShort Method 
        field.setShort(emp, (short)134); 
  
        // print value of uniqueNo 
        System.out.println( 
            "Value of uniqueNo after "
            + "applying setShort is "
            + emp.uniqueNo); 
    } 
} 
  
// sample class 
class Employee { 
  
    // static short values 
    public static short uniqueNo = 239; 
}
输出:
Value of uniqueNo before applying setShort is 239
Value of uniqueNo after applying setShort is 134

示例2:

// Java Program to illustrate setShort() method 
  
import java.lang.reflect.Field; 
  
public class GFG { 
  
    public static void main(String[] args) 
        throws Exception 
    { 
  
        // create Numbers object 
        Numbers no = new Numbers(); 
  
        // Get the value field object 
        Field field 
            = Numbers.class.getField("value"); 
  
        // Apply setShort Method 
        field.setShort(no, (short)5366); 
  
        // print value of isActive 
        System.out.println( 
            "Value after "
            + "applying setShort is "
            + Numbers.value); 
    } 
} 
  
// sample Numbers class 
class Numbers { 
  
    // static short value 
    public static short value = 13685; 
}
输出:
Value after applying setShort is 5366

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



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 Field setShort() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。