Given two classes A and B with one-argument constructors and a binary function f, I need to parse strings of the form
"f(A(10), B(20))"
"f(A(2), A(3))"
create the appropriate instances and call the respective functions:
class Functions {
public static double f(A a1, A a2);
public static double f(A a, B b);
public static double f(B b1, B b2);
// ...
}
So what I am looking for is a method of the kind
T createInstanceFromString(String desc);
to create the instances from strings like “A(10)” or “B(20)”. Of course and unfortunately, this is impossible in Java.
Any advice on solutions to this problem are greatly appreciated.
Edit: I forgot to mention that there is a potentially large number of different classes A, B, C, etc and a large number of functions f, g, etc. I’d like to use createInstanceFromString to separate the parsing from calling, otherwise one has to conditionally parse separately for each function call, which would bring a lot of code duplication.
Edit2: The question is not about how to parse, but about how to parse and then return an instance in a general purpose method/factory/whatever.
You need to tokenize the String.
(if it always starts with
f(and ends with)you can make your life easier, be removing these parts).A(4) -> Find the Classname -> A -> find the Parameter -> 4
This is done like this (pseudo java code):
Maybe, this lik is helpful: http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
update
This is like writing a compiler. You can get further information, if you read something about, how to write a compiler: http://en.wikipedia.org/wiki/Compiler
update 2
put all generated instances into an array. Now you can get the correct method f with the reflections-API. The Code will be something like
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getDeclaredMethod(java.lang.String, java.lang.Class…)