0

Bear with me on this one... I'm having a little trouble finding the words to explain what I want to do.

I have 26 classes. Each of which have methods with the same name, return type and parameters. The class names are aWord(), bWord(), cWord etc.

The methods accept a single char as a parameter and return a String[].

The following code works, but is super lengthy, and I would have to do it every time I want a different method:

if (firstChar == 'a'){aWord word = new aWord(); wordArray = word.returnWordArray();}
else if (firstChar == 'b'){bWord word = new bWord(); wordArray = word.returnWordArray();}
    else if (firstChar == 'c'){cWord word = new cWord(); wordArray = word.returnWordArray();}
    else if (firstChar == 'd'){dWord word = new dWord(); wordArray = word.returnWordArray();}

Ideally, I'd be able to have something like:

String className = char + "Word";
className thisClass = new className();

String[] stringy = className.returnWordArray();

Any idea what a) I'm talking about and b) how I would go about doing it?

Heinz
  • 75
  • 1
  • 9
  • One thought is that instead of having to create 26 objects, you could always make the methods `static`. Then you would just have to call them using the class name. – Logan Dec 06 '16 at 13:56
  • 5
    Why 26 classes? Wouldnt 26 instances of ONE class good enough? – Gyro Gearless Dec 06 '16 at 13:57
  • 1
    Possible duplicate of [What is reflection and why is it useful?](http://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful) – Florent Bayle Dec 06 '16 at 13:57
  • 1
    Sounds like you want to do a bit of metaprogramming to me. You won't be altogether that lucky with java though. You could of course abbreviate all of this a bit by simply creating the instance within a `switch`-clause and afterwards calling `returnWordArray`. If they don't inherit the same class, your best shot would be reflection. I'd definitely start searching for a completely different approach than what you use. –  Dec 06 '16 at 13:57
  • Maybe you want to take a look at Factory Create software pattern which is basically what you want to do – k_kaz Dec 06 '16 at 13:58

1 Answers1

2

You could achieve this with reflection.

String className = char + "Word";
Class c = Class.forName("com.yourWholePackage." + className);
Object obj = c.newInstance(); // get Instance
Method method = c.getDeclaredMethod("returnWordArray");
String[] stringy = (String[]) method.invoke(obj);

Besides that to simplify your if-else you could use switch-case and ultimately a different pattern like Factory or even Inheritance

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107