Home > Java > javaTutorial > body text

Java reflection calls the method of the specified attribute

WBOY
Release: 2023-04-27 16:19:15
forward
1367 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 calls the method of the specified attribute. 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