CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2010
    Posts
    1

    Calling a method with a variable in the methodname

    Hi everyone!

    Is it possible in Java to call a method in a loop with a variable in the methods name.

    For Example (just for explanation):

    Code:
    public void func1() {}
    
    public void func2() {}
    
    public void func3() {}
    
    public void hereicall() {
         for (int i=1; i<4; i++) func`i`();
    }
    Thanx for the answers

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Calling a method with a variable in the methodname

    Yes. It's not a straightforward as your example but it is possible.

    Actually there are a few ways of doing this sort of thing depending on what you are trying to achieve. Often the best approach to this type of problem is to have another look at your design and see if you can solve the problem using polymorphism. If this isn't possible then you are into reflection: You get the Class of the object you are dealing with and use one of the available methods to get a Method object for the method call you want to make and then you call its invoke(..) method.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured