java char 范例_Java Field setChar()用法及代码示例

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

用法:

public void setChar(Object obj, char c)

throws IllegalArgumentException,

IllegalAccessException

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

obj:是应该修改其字段的对象,并且

c:这是要修改的obj字段的新值。

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

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

IllegalAccessException:如果此Field对象正在强制执行Java语言访问控制,并且基础字段是不可访问的或最终的。

IllegalArgumentException:如果指定的对象不是声明基础字段(或其子类或实现者)的类或接口的实例,或者展开转换失败。

NullPointerException:如果指定的对象为null,并且该字段是实例字段。

ExceptionInInitializerError:如果此方法引发的初始化失败。

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

示例1:

// Java program to illustrate setByte() method

// program illustrate setChar()

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 lastNamePrefix

System.out.println(

"Value of lastNamePrefix before "

+ "applying setChar is "

+ emp.lastNamePrefix);

// Get the marks field object

Field field = Employee.class

.getField("lastNamePrefix");

// Apply setChar Method

field.setChar(emp, 'B');

// print value of lastNamePrefix

System.out.println(

"Value of lastNamePrefix after "

+ "applying setChar is "

+ emp.lastNamePrefix);

// print value of firstNamePrefix

System.out.println(

"Value of firstNamePrefix before "

+ "applying setChar is "

+ emp.firstNamePrefix);

// Get the marks field object

field = Employee.class

.getField("firstNamePrefix");

// Apply setChar Method

field.setChar(emp, 'Z');

// print value of firstNamePrefix

System.out.println(

"Value of firstNamePrefix after "

+ "applying setChar is "

+ emp.firstNamePrefix);

}

}

// sample class

class Employee {

// static char values

public static char firstNamePrefix = 'A';

public static char lastNamePrefix = 'S';

}

输出:

Value of lastNamePrefix before applying setChar is S

Value of lastNamePrefix after applying setChar is B

Value of firstNamePrefix before applying setChar is A

Value of firstNamePrefix after applying setChar is Z

示例2:

// Java program to illustrate setChar() method

import java.lang.reflect.Field;

public class GFG {

public static void main(String[] args)

throws Exception

{

// create user object

User user = new User();

// Get the id field object

Field field = User.class

.getField("id");

// Apply setChar Method

field.setChar(user, 'A');

// print value of isActive

System.out.println("Value after "

+ "applying setChar is "

+ user.id);

}

}

// sample User class

class User {

// static char values

public static char id = 'Z';

}

输出:

Value after applying setChar is A

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值