第一步:创建一个枚举类
MYSQL_DRIVER("mysql","optimization.ifelse.strategy.MySqlStrategy"), ORCAL_DRIVER("orcal","optimization.ifelse.strategy.OrcalStrategy"), SQLSERVER_DRIVER("sqlserver","optimization.ifelse.strategy.SqlServerStrategy"), HBASE_DRIVER("hbase","optimization.ifelse.strategy.HbaseStrategy"), MONGO_DRIVER("mogon","optimization.ifelse.strategy.MongoStrategy"), ; private String type; private String clazz; private DbTypeEnum(String type,String clazz){ this.type=type; this.clazz=clazz; } public String type() { return type; } public String clazz(){ return clazz; }
第二步:
private static Map<String,String> strategyMap = new HashMap<>(); public static void excuteStrategy(String type){ for (DbTypeEnum t : DbTypeEnum.values()) { strategyMap.put(t.type(), t.clazz()); } String class_path=strategyMap.get(type); try { /* * 通过反射将RefelDbTypeEnum中映射的类实例化 * */ Class clazz=Class.forName(class_path); Method excute =clazz.getDeclaredMethod("excute"); excute.invoke(clazz.newInstance()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } }