package Reflects; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; /** * 通过反射实现如下操作 * Actor a = new Actor * a.name = "张三"; * a.age = 20; * a.sex ="男"; * System.out.println(a); */ public class ReflectDemo{ public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException { Class<?> objClass = Class.forName("Reflects.Actor"); //类对象 Constructor<?> constructor = objClass.getConstructor();//获取构造方法 Object o = constructor.newInstance();//生成对象 Field name = objClass.getField("name"); Field age = objClass.getField("age"); Field sex = objClass.getField("sex"); name.set(o,"张三"); age.set(o,20); sex.set(o,"男"); System.out.println(o); } }