反射的作用:绕过编译阶阶段
package reflect_framework; /** * FileName: ReflectDemo * Author: lps * Date: 2022/4/22 10:32 * Sign:刘品水 Q:1944900433 */ public class ReflectDemo { public static void main(String[] args) { Student s = new Student(); s.setName("刘品水"); s.setClassName("物联网1913"); s.setAge(21); s.setSex('男'); s.setHobby("敲键盘"); MybatisUtil.save(s); Teacher t = new Teacher(); t.setName("仲老师"); t.setSex('男'); t.setSalary(28888.88); MybatisUtil.save(t); } }
package reflect_framework; import java.io.FileOutputStream; import java.io.PrintStream; import java.lang.reflect.Field; /** * FileName: MybatisUtil * Author: lps * Date: 2022/4/22 10:46 * Sign:刘品水 Q:1944900433 */ public class MybatisUtil { public static void save(Object obj) { //1.提取这个对象的全部成员变量 try (PrintStream ps = new PrintStream(new FileOutputStream("F:\\JavaProject\\Code\\src\\data.txt",true));){ Class<?> c = obj.getClass(); //String getSimpleName() 返回源代码中给出的基础类的简单名称。 ps.println("========"+c.getSimpleName()+"========"); //提取全部成员变量 Field[] fields = c.getDeclaredFields(); //获取成员变量的信息 for (Field field : fields) { String name = field.getName(); //提取本成员变量在obj对象的值 field.setAccessible(true); String value= field.get(obj)+""; ps.println(name+"="+value); } } catch (Exception e) { e.printStackTrace(); } } }
package reflect_framework; /** * FileName: Student * Author: lps * Date: 2022/4/22 10:31 * Sign:刘品水 Q:1944900433 */ public class Student { private String name; private char sex; private int age; private String className; private String hobby; public Student() { } public Student(String name, char sex, int age, String className, String hobby) { this.name = name; this.sex = sex; this.age = age; this.className = className; this.hobby = hobby; } public String getName() { return name; } public void setName(String name) { this.name = name; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } }
package reflect_framework; /** * FileName: Teacher * Author: lps * Date: 2022/4/22 10:31 * Sign:刘品水 Q:1944900433 */ public class Teacher { private String name; private char sex; private double salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public Teacher() { } public Teacher(String name, char sex, double salary) { this.name = name; this.sex = sex; this.salary = salary; } }