1

I have a populated object(animalObj) of class Animal.

Animal class have methods like

  1. getAnimal1()
  2. getAnimal2() etc.

So i need to dynamically call these method FROM the object animalObj.

what i required is the implementation of this

String abc="123";
for(int i=0; i<abc.length(); i++)
   animalObj.getAnimal+abc.charAt(i)+();

I know the about code is rubbish, but i need to know how to implement this.

I read about reflection in java and saw some questions like Java dynamic function calling, How do I invoke a Java method when given the method name as a string?.

But here all the questions are not dealing with populated object.

Any suggestions?

Community
  • 1
  • 1
abyin007
  • 335
  • 1
  • 3
  • 13

3 Answers3

2
try {
 animalObj.getClass().getMethod("getAnimal"+abc.charAt(i)).invoke(animalObj);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}
Optional
  • 4,081
  • 3
  • 22
  • 42
  • thanks this is working.. :-) I think, in your example there is no need to assign it to method object right? since u are already invoking it. – abyin007 Jun 12 '13 at 10:09
1

Try with reflection:

String methodName = "getAnimal" + abc.length();
try {
    animalObj.getClass().getMethod(methodName).invoke(animalObj);
} catch (SecurityException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
    throw new IllegalArgumentException("Could not call " + methodName 
        + ": " + ex.getMessage(), ex);
}

The multicatch is Java 7 syntax, if you don't use Java 7, you can catch the individual exceptions or just Exception.

stivlo
  • 77,013
  • 31
  • 135
  • 193
0

You can use reflection but it will make your rubbish code even more rubbish. The right way to do it is to refactor each of the getAnimal? methods into their own class which extends one common class. E.g.

interface GetAnimalWrapper{ void getAnimal(); }

GetAnimalWrapper animal1 = new GetAnimalWrapper(){ void getAnimal(){ /* something */ } };

GetAnimalWrapper animal2 = new GetAnimalWrapper(){ void getAnimal(){ /* something else */ } };

Now you can have an array of GetAnimalWrapper objects:

animObj.animArr = {animal1, animal2};

for(int i=0; i<2; i++) animObj.animArr[i].getAnimal();

Community
  • 1
  • 1
RFon
  • 118
  • 6