Home > Java > javaTutorial > Java Reflection: How to call specific properties?

Java Reflection: How to call specific properties?

PHPz
Release: 2023-04-26 21:55:06
forward
869 people have browsed it

Explanation

1. In the reflection mechanism, you can directly operate the attributes in the class through the Field class.

2. Set and obtain attribute content through the set() and get() methods provided by the Field class.

Example

@Test
public void testField() throws Exception {
    Class clazz = Person.class;
 
    //创建运行时类的对象
    Person p = (Person) clazz.newInstance();
 
    //1. getDeclaredField(String fieldName):获取运行时类中指定变量名的属性
    Field name = clazz.getDeclaredField("name");
 
    //2.保证当前属性是可访问的
    name.setAccessible(true);
    //3.获取、设置指定对象的此属性值
    name.set(p,"Tom");
 
    System.out.println(name.get(p));
}
Copy after login

The above is the detailed content of Java Reflection: How to call specific properties?. 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