反射在数据库读写中的应用
MySQLDao.java
package cn.sgy.reflection1.exer; public class MySQLDao implements Dao{ @Override public void insert(User user) { System.out.println("向MySQL插入用户对象:"+ user.getName()); } @Override public void delete(User user) { System.out.println("从MySQL中删除用户对象:"+ user.getName()); } }
User.java
package cn.sgy.reflection1.exer; import java.sql.Date; public class User { private String name; private int age; private char gender; private Date birth; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } }
OracleDao.java
package cn.sgy.reflection1.exer; public class OracleDao implements Dao{ @Override public void insert(User user) { System.out.println("向Oracle中插入用户:"+ user.getName()); } @Override public void delete(User user) { System.out.println("从Oracle中删除用户:"+ user.getName()); } }
Service.java
package cn.sgy.reflection1.exer; public class Service { private Dao dao = DaoFactory.getFactory().getDaoInsance(); public void insert() { User user = new User(); dao.insert(user); } public void delete() { User user = new User(); dao.delete(user); } public static void main(String[] args) throws Exception { while (true) { Service s = new Service(); s.insert(); Thread.sleep(10000); } } }
DaoFactory.java
package cn.sgy.reflection1.exer; import java.io.FileInputStream; import java.util.Properties; //工厂模式 public class DaoFactory { private static DaoFactory factory = new DaoFactory(); private Properties p = new Properties(); private DaoFactory() { } public static DaoFactory getFactory() { return factory ; } @SuppressWarnings("unchecked") public Dao getDaoInsance() { try { p.load(new FileInputStream("config.properties")); String name = p.getProperty("Dao"); Class<Dao> clz = (Class<Dao>) Class.forName(name); return clz.newInstance(); } catch (Exception e) { e.printStackTrace(); } return null; } }