Suppose I have classes Circle, Rectangle, and Triangle.
Based on input from a data file, I want to create the appropriate object. For instance, if the first line of shapes.dat
is C.5 0 0
, I will create a Circle object with radius 5. If the next line is R.5 3 0
, I will create a Rectangle object with length 5 and width 3.
I know I could use basic if-else logic, but I was wondering whether there's a way to use the string as a means of instantiating a new object. Sort of like the exec()
method in Python. Here's the code snippet describing what I want:
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); //???
...
}