DemoObject : 單純的物件
package dynamic;
public class DemoObject {
private int id ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Main.java : 程式執行的地方.
package dynamic;
import java.io.IOException;
import java.util.Properties;
public class Main {
public static void main(String [] args) throws IOException{
Properties properties = new Properties();
properties.load(Main.class.getResourceAsStream("object_name.prop"));
String classFullName = (String) properties.get("objectName");
try {
Class clazz = Class.forName(classFullName);
DemoObject dObj = (DemoObject)clazz.newInstance();
dObj.setId(1);
System.out.println(dObj.getId());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
object_name.prop : 用key - value 的方式記錄完整的類別名稱.
objectName = dynamic.DemoObject
沒有留言:
張貼留言