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?

3
  • 2
    Try searching Java Reflections. Commented Jun 12, 2013 at 9:41
  • What do you mean "But here all they dont have a populated object."? Commented Jun 12, 2013 at 9:44
  • 4
    Bad code design. Pass the i to the method instead. Commented Jun 12, 2013 at 9:45

3 Answers 3

2
try {
 animalObj.getClass().getMethod("getAnimal"+abc.charAt(i)).invoke(animalObj);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.