【发布时间】:2018-01-23 15:23:08
【问题描述】:
假设我有 Circle、Rectangle 和 Triangle 类。
根据来自数据文件的输入,我想创建适当的对象。比如shapes.dat的第一行是C.5 0 0,我将创建一个半径为5的Circle对象。如果下一行是R.5 3 0,我将创建一个长5宽3的Rectangle对象。
我知道我可以使用基本的 if-else 逻辑,但我想知道是否有办法使用字符串作为实例化新对象的方法。有点像 Python 中的 exec() 方法。这是描述我想要的代码sn-p:
Scanner file = new Scanner (new File("shapes.dat"));
String s;
Map<Character,String> dict = new HashMap<Character,String>();
dict.put('C', "Circle");
dict.put('R', "Rectangle");
dict.put('T', "Triangle");
while (file.hasNextLine())
{
s = file.nextLine().trim();
String name = dict.get(s.toCharArray()[0]);
String data = s.split(".")[1];
String code = name + " x = new " + name + "(data);";
SYS.exec(code); //???
...
}
【问题讨论】:
-
你想在运行时创建一个实例?
-
@Ravi 是的,没错。
-
您可以尝试为每种形状创建类
-
在不使用
else-if/switch的情况下创建一个新实例是有风险的并且容易出现错误,但如果你必须这样做,this 可能会有所帮助。