-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflectFactoryDemo.java
More file actions
74 lines (62 loc) · 1.43 KB
/
Copy pathReflectFactoryDemo.java
File metadata and controls
74 lines (62 loc) · 1.43 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
* ½«·´ÉäÓÃÓÚ¹¤³§Ä£Ê½
*/
package com.java.study;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class ReflectFactoryDemo {
public static void main(String[] args) throws FileNotFoundException,
IOException {
/*
* fruit f = Factory.getInstance("com.java.study.Apple"); f.eat();
*/
Properties prpt = Init.getPrpt();
fruit f = Factory.getInstance(prpt.getProperty("apple"));
f.eat();
}
}
interface fruit {
public abstract void eat();
}
class Apple implements fruit {
@Override
public void eat() {
System.out.println("Apple");
}
}
class Orange implements fruit {
@Override
public void eat() {
System.out.println("Orange");
}
}
class Factory {
public static fruit getInstance(String className) {
fruit f = null;
try {
f = (fruit) Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return f;
}
}
class Init {
public static Properties getPrpt() throws FileNotFoundException,
IOException {
Properties prpt = new Properties();
File f = new File("fruit.properties");
if (f.exists()) {
prpt.load(new FileInputStream(f));
} else {
prpt.setProperty("apple", "com.java.study.Apple");
prpt.setProperty("orange", "com.java.study.Orange");
prpt.store(new FileOutputStream(f), "FRUIT CLASS");
}
return prpt;
}
}