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)); }
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!