【Java高级】反射+工厂模式+属性文件的实例应用


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高级】反射+工厂模式+属性文件的实例应用)