abyin007
abyin007

Reputation: 401

How to call Java function of an object when function name is stored in a string variable?

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?

Upvotes: 1

Views: 1947

Answers (3)

Optional
Optional

Reputation: 4507

try {
 animalObj.getClass().getMethod("getAnimal"+abc.charAt(i)).invoke(animalObj);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}

Upvotes: 2

RFon
RFon

Reputation: 118

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();

Upvotes: 0

stivlo
stivlo

Reputation: 85496

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.

Upvotes: 1

Related Questions