java 使用反射技术解耦
Posted MarcoReus
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 使用反射技术解耦相关的知识,希望对你有一定的参考价值。
1.调用的代码 /src/de/test.java
package de; public class Test { public static void main(String[] args) { Dao dao = DaoFactory.getInstance().getImpl("impl", Dao.class); dao.show(); }
2.配置文件/src/config/config.properties
impl=de.DaoImpl1
3.接口和2个实现类 (/src/de/Dao.java,DaoImpl1.java,DaoImpl2.java
package de; public interface Dao { void show(); }
package de; public class DaoImpl1 implements Dao { @Override public void show() { System.out.println(this.getClass().getSimpleName()); } }
package de; public class DaoImpl2 implements Dao { @Override public void show() { System.out.println(this.getClass().getSimpleName()); } }
4.解耦类(单例工厂)
package de; import java.io.InputStream; import java.util.Properties; public class DaoFactory { private static DaoFactory instance = new DaoFactory(); public static DaoFactory getInstance() { return instance; } public <T> T getImpl(String key, Class<T> clazz) { try { Properties properties = new Properties(); properties.load(DaoFactory.class.getClassLoader().getResourceAsStream("config/config.properties")); return (T) Class.forName(properties.getProperty(key)).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } }
以上是关于java 使用反射技术解耦的主要内容,如果未能解决你的问题,请参考以下文章