反射获取成员变量并使用练习1
public class ReflectDemo02 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException { //获取Class对象 Class<?> c = Class.forName("com.reflect_02.Student"); //获取构造方法对象 Constructor<?> con = c.getConstructor(); Object obj = con.newInstance(); System.out.println(obj); //获取成员变量对象 Field nameField = c.getDeclaredField("name"); nameField.setAccessible(true); nameField.set(obj,"旭旭宝宝"); System.out.println(obj); Field ageField = c.getDeclaredField("age"); ageField.setAccessible(true); ageField.set(obj,35); System.out.println(obj); Field addressField = c.getDeclaredField("address"); addressField.setAccessible(true); addressField.set(obj,"东营"); System.out.println(obj); } }
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。