public interface Fruit {
public void showColor();
}
public class Apple implements Fruit {
public void showColor() {
// TODO Auto-generated method stub
System.out.println("Apple is red");
}
}class FruitFactory {
public static Fruit produceFruit(String clsName) {
try {
System.out.println("1");
Class<?> cls = Class.forName("com.loadandreflect.test."+clsName);
System.out.println("2");
return (Fruit) cls.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public class MainTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties properties = new Properties();
try {
properties.load(new FileInputStream(new File(
"FruitParam.properties")));
String fruitName=(String) properties.get("apple");
Fruit fruit=FruitFactory.produceFruit(fruitName);
fruit.showColor();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
本文通过一个具体的Java程序示例介绍了如何使用反射机制创建对象,并结合工厂模式实现了一个可扩展的水果颜色显示功能。该程序定义了一个Fruit接口及其实现类Apple,通过配置文件指定类名来实例化不同的水果对象。
1136

被折叠的 条评论
为什么被折叠?



