vendredi 30 janvier 2015

Using Java Reflection to determine which class to instantiate

There is a Message superclass and there are various Message subclasses like WeddingMessage, GreetingMessage, FarewellMessage, Birthday Message.


The Message superclass has a constructor:



public Message(String messageType){
this.messageType = messageType;
}


The message subclasses all have different constructors, but they all make a call to the superclass, where they pass the messageType as an argument So for example:



public BirthdayMessage( String name, int age){
super("birthday");
System.out.println("Happy birthday " + name + "You are " + age " years old");

public FareWellMessage(String name, String message){
super("farewell");
System.out.println(message + " " + name);
}


The messageType which is created is determined by arguments passed in by the user. So for example, if a user inserts 'birthday John 12', then a BirthdayMessage will be created with parameters John and 12. If a user enters 'farewell Grace take care' then an instance of FarewellMessage is created with those parameters.


Instead of having a bunch of if/else statements or a switch case, in the form of something like-



words[] = userinput.slice(' ');
word1 = words[0];
if (word1 == birthday)
create new BirthdayMessage(parameters here)
if (word1 == wedding)
create new weddingMessage(parameters here)


etc


How could i use reflection to determine which type of Message class to create. My current idea is to use the File class to get all the Files in the package which contain the message subclasses. Then use reflection to get each of their constructor parameter types and see if they match the parameters given by user input. Then make instances of those matching classes with random parameters. When made, the subclass will make a call to its superclass constructor with its messageType. Then i can check to see if the messageType variable matches the user input.


So if the user enters 'birthday john 23' I find all constructors in the package that take a String and an int as parameters and that have a field messageType(inherited from Message). Then i create an instance of that class and check if the messageType is == to the first word in the user input (birthday in this case). If it is, then i create an instance of that class with the user provided parameters.


Is there a better way to do this with reflection?


Aucun commentaire:

Enregistrer un commentaire