本例演示如何結合 Java 反射、Properties 配置文件與工廠模式,實現根據配置動態創建對象,實現「修改配置、不改代碼」的解耦效果。
interface Fruit {
void eat();
}
class Apple implements Fruit {
public void eat() { System.out.println("eat Apple"); }
}
class Orange implements Fruit {
public void eat() { System.out.println("eat Orange"); }
}
class ConfigManager {
public static Properties loadConfig() throws IOException {
Properties props = new Properties();
File file = new File("fruit.properties");
if (file.exists()) {
props.load(new FileInputStream(file));
} else {
// 默認配置
props.setProperty("apple", "reflect.Apple");
props.setProperty("orange", "reflect.Orange");
props.store(new FileOutputStream(file), "FRUIT CLASS");
}
return props;
}
}
class FruitFactory {
public static Fruit getInstance(String className) {
try {
return (Fruit) Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public class Main {
public static void main(String[] args) {
try {
Properties props = ConfigManager.loadConfig();
Fruit fruit = FruitFactory.getInstance(props.getProperty("apple"));
if (fruit != null) fruit.eat();
} catch (IOException e) {
e.printStackTrace();
}
}
}
有配置文件!
eat Apple
clazz.getDeclaredConstructor().newInstance())。ClassNotFoundException、InstantiationException、IllegalAccessException 等。ServiceLoader 機制替代手工配置,符合 Java SPI 規範。反射賦予 Java 動態性,配合工廠模式與外部配置,是構建可擴展框架的基石。本例雖簡單,但包含了反射實戰的核心要素。