Home > Java > javaTutorial > How to access member variables in java

How to access member variables in java

WBOY
Release: 2023-05-27 14:51:15
forward
2148 people have browsed it

Through the getField() method of the Class object, you can obtain all or specified member variables Field included in this class. Field provides the following two methods to read and set member variable values.

1. getxx(Objectobj):

Get the member variable value of the obj object. The xxx here corresponds to the basic type in 8. If the type of the member variable If it is a reference type, cancel the xxx

2 and setxx(Objectobj, xxxval) after get:

Set the member variable value of the obj object to the val value. The xxx here corresponds to 8 basic types. If the member type is a reference type, cancel the xxx

3 and instance

 Person person = new Person();
 // 获取name成员变量Field
 Field nameField = person.getClass().getDeclaredField("name");
 // 启用访问控制权限
 nameField.setAccessible(true);
 // 获取person对象的成员变量name的值
 String name = (String) nameField.get(person);
 System.out.println("name = " + name);
 // 设置person对象的成员变量name的值
 nameField.set(person, "lisi");
 System.out.println(person);
Copy after login

What collection classes are there in Java?

Collections in Java are mainly divided into four categories:

1. List: ordered, repeatable;

2. Queue: ordered, repeatable Duplicate;

3. Set collection: non-repeatable;

4. Map: unordered, with unique keys and non-unique values.

The above is the detailed content of How to access member variables in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template