1.创建User.java
package com.tao.test; public class User { private String name; private 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.main方法
package com.tao.test; import java.lang.reflect.Constructor; import java.lang.reflect.Field; public class test { public static void main(String[] args) throws Exception, SecurityException { //第一种 Constructor<?>方法 Constructor<?> a = User.class.getDeclaredConstructor(); a.setAccessible(true); User b = (User)a.newInstance(); b.setId(1);//id字段 b.setName("test");//name字段 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); Object o = c.newInstance(); idF.set(o, 2); Field nameF = c.getDeclaredField("name");//name字段 nameF.setAccessible(true); Object name = c.newInstance(); nameF.set(name, "jack"); System.out.println(idF.get(o)+" "+nameF.get(name)); //普通new User user = new User(); user.setId(3); user.setName("tery"); System.out.println(user.getId()+" "+user.getName()+" "+user.getClass()); } }
3.控制台输出:
1 test 2 jack 3 tery class com.tao.test.User