反射的应用实例
接口
1 2 3 4
| public interface Fruit { void squeeze(); }
|
水果实体类
1 2 3 4 5 6
| public class Apple implements Fruit{ @Override public void squeeze() { System.out.println("榨一杯苹果汁"); } }
|
1 2 3 4 5 6
| public class Banana implements Fruit{ @Override public void squeeze() { System.out.println("榨一杯香蕉汁"); } }
|
1 2 3 4 5 6
| public class Orange implements Fruit{ @Override public void squeeze() { System.out.println("榨一杯橘子汁"); } }
|
榨汁类,榨汁方法
1 2 3 4 5 6 7
| public class Juicer { public void run(Fruit f) { f.squeeze(); } }
|
测试方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import org.junit.Test;
import java.io.File; import java.io.FileInputStream; import java.lang.reflect.Constructor; import java.util.Properties;
public class FruitTest { @Test public void test() throws Exception { Properties pros = new Properties(); File file = new File("src/config.properties"); FileInputStream fis = new FileInputStream(file); pros.load(fis); String fn = pros.getProperty("fruitName"); Class clazz = Class.forName(fn); Constructor co = clazz.getDeclaredConstructor(); co.setAccessible(true); Fruit fruit = (Fruit) co.newInstance(); Juicer juicer = new Juicer(); juicer.run(fruit); } }
|
此案例体现了反射动态的特性,在此案例中,实体类的对象是未定义的,通过配置文件config.properties来通过反射获取具体是哪一个类的对象来调用方法