samedi 31 janvier 2015

Using reflection to call the right constructor where parameters are supplied by the user

Lets say there is a class with multiple constructors which take a different number of Strings and ints. e.g. (String, int) or (String, String, int) or (int, int, int) The user supplies some text such as 'Hello 4 Goodbye 7' I then need to use reflection to create an instance of the Class using the constructor with the parameters supplied by the user i.e.(String, int, String, int)` How would i go about doing this?


My idea so far is to slice the user input into an array userInput[]. Then i have another array parameterTypes[]. If userInput[0] can be parsed to an int, i save "Integer.TYPE" into parameterTypes[0]. Otherwise, i save "String.class". The next bit is the part i am struggling with. My idea is to use reflection to get Declared-constructors. Then for each constructor, get ParaMeterTypes and see which one matches the types in my parameterTypes array. But i'm not sure how i can compare the Strings i've saved in parameterTypes and the parameterTypes obtained through reflection.






Aucun commentaire:

Enregistrer un commentaire