1. 创建 user.java
пакет com.tao.test; public class user {private String name; частный INT ID; public user () {} public String getName () {return name; } public void setName (string name) {this.name = name; } public int getId () {return id; } public void setId (int id) {this.id = id; }}2. Мейн 方法
пакет com.tao.test; импортировать java.lang.reflect.constructor; import java.lang.reflect.field; public class test {public static void main (string [] args) выбрасывает исключение, SecurityException {// 第一种 Constructor <?> 方法 Contructor <?> a = user.class.getDeclAderConstructoror (); A.SetAccessible (True); Пользователь B = (пользователь) A.NewInstance (); b.setid (1); // id 字段 b.setname ("test"); // имя 字段 System.out.println (b.getid ()+""+b.getName ()); // 第二种 Class <?> 方法 Class <?> C = class.forname ("com.tao.test.user"); Field IDF = C.GetDeclaredField ("id"); // id 字段 idf.setAccessible (true); Объект o = c.newinstance (); idf.set (o, 2); Field namef = c.getDeclaredfield ("name"); // имя 字段 namef.setAccessible (true); Имя объекта = c.newinstance (); namef.set (имя, "Джек"); System.out.println (idf.get (o)+""+namef.get (name)); // 普通 Новый пользователь пользователь = новый пользователь (); user.setid (3); user.setname ("tery"); System.out.println (user.getId ()+""+user.getName ()+""+user.getClass ()); }}3. : :
тест
Джек
Tery Class com.tao.test.user
总结
以上所述是小编给大家介绍的 java 反射的两种使用方法 希望对大家有所帮助 , 如果大家有任何疑问请给我留言 , 小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!