java boolean例子_Java Field setBoolean()用法及代码示例
java.lang.reflect.Field的setBoolean()方法用于將字段的值設(shè)置為指定對(duì)象上的布爾值。當(dāng)需要將對(duì)象的字段的值設(shè)置為布爾值時(shí),可以使用此方法在對(duì)象上設(shè)置值。
用法:
public void setBoolean(Object obj, boolean z)
throws IllegalArgumentException,
IllegalAccessException
參數(shù):此方法接受兩個(gè)參數(shù):
obj:是應(yīng)該修改其字段的對(duì)象,并且
z:這是要修改的obj字段的新值。
返回值:此方法不返回任何內(nèi)容。
異常:此方法引發(fā)以下異常:
IllegalAccessException:如果此Field對(duì)象正在實(shí)施Java語(yǔ)言訪問控制,并且基礎(chǔ)字段是不可訪問的或最終的。
IllegalArgumentException:如果指定的對(duì)象不是聲明基礎(chǔ)字段(或其子類或?qū)崿F(xiàn)者)的類或接口的實(shí)例,或者展開的轉(zhuǎn)換失敗。
NullPointerException:如果指定的對(duì)象為null并且該字段是實(shí)例字段。
ExceptionInInitializerError:如果此方法引發(fā)的初始化失敗。
以下示例程序旨在說明setBoolean()方法:
示例1:
// Java program to illustrate setBoolean() method
import java.lang.reflect.Field;
public class GFG {
public static void main(String[] args)
throws Exception
{
// create user object
User user = new User();
// print value of isActive
System.out.println("Value before "
+ "applying setBoolean is "
+ user.isActive);
// Get the marks field object
Field field
= User.class
.getField("isActive");
// Apply setBoolean Method
field.setBoolean(field, false);
// print result
System.out.println("Value after "
+ "applying setBoolean is "
+ user.isActive);
}
}
// sample User class
class User {
// static boolean values
public static boolean isActive = true;
}
輸出:
Value before applying setBoolean is true
Value after applying setBoolean is false
示例2:
// Java program to illustrate setBoolean() 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 isManager
System.out.println("Value of isManager before "
+ "applying setBoolean is "
+ emp.isManager);
// Get the marks field object
Field field
= Employee.class
.getField("isManager");
// Apply setBoolean Method
field.setBoolean(emp, false);
// print value of isActive
System.out.println("Value of isPresent before "
+ "applying setBoolean is "
+ emp.isManager);
// print value of isManager
System.out.println("Value of isManager before "
+ "applying setBoolean is "
+ emp.isPresent);
// Get the marks field object
field = Employee.class
.getField("isPresent");
// Apply setBoolean Method
field.setBoolean(emp, true);
// print value of isActive
System.out.println("Value of isPresent before "
+ "applying setBoolean is "
+ emp.isPresent);
}
}
// sample User class
class Employee {
// static boolean values
public static boolean isPresent = false;
public static boolean isManager = true;
}
輸出:
Value of isManager before applying setBoolean is true
Value of isPresent before applying setBoolean is false
Value of isManager before applying setBoolean is false
Value of isPresent before applying setBoolean is true
總結(jié)
以上是生活随笔為你收集整理的java boolean例子_Java Field setBoolean()用法及代码示例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 颐和园出门要验票吗?
- 下一篇: java sampling_Java机器