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
相關用法
- Java Array setShort()用法及代碼示例
- Java Field set()用法及代碼示例
- Java Field get()用法及代碼示例
- Java Field setDouble()用法及代碼示例
- Java Field setChar()用法及代碼示例
- Java Field setFloat()用法及代碼示例
- Java Field getByte()用法及代碼示例
- Java Field toGenericString()用法及代碼示例
- Java Field isSynthetic()用法及代碼示例
- Java Field setInt()用法及代碼示例
- Java Field getInt()用法及代碼示例
- Java Field getLong()用法及代碼示例
- Java Field hashCode()用法及代碼示例
- Java Field getType()用法及代碼示例
- Java Field setBoolean()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Field setShort() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。