0

I want to do something like this:

for(int i = 0; i<5;i++)
    {
        public void test[i]()
        {
            System.out.println(i);
        }   
    }

Can I even create methods like this? I know it requires an array but I have read everywhere about method arrays and it doesn't do it like I want it to.

I don't want to make several methods and then save them in an array, I want to create methods in a loop, and I don't know how to do this.

I need it so I can make as many methods I want of this certain method, instead of writing 100 methods.

Duncan Jones
  • 63,838
  • 26
  • 184
  • 242
Ploug
  • 25
  • 1
  • 1
  • 6
  • Err no idea what you're trying to do. – Tudor Oct 26 '12 at 10:04
  • 1
    First of all you cannot create even a normal method in a loop like that. Secondly you need to be more specific, what exactly you want to do. Keep aside the method for a while. – Rohit Jain Oct 26 '12 at 10:05
  • Why create duplicate method? I think its not possible in Java. You can call the same method several times. – Subir Kumar Sao Oct 26 '12 at 10:05
  • And how do you intend to call these methods you're creating? – Tudor Oct 26 '12 at 10:06
  • Why can't you just remove that method, and just let the `sysout` do its work? – Rohit Jain Oct 26 '12 at 10:06
  • Reason why i cant just remove that method is because obviously the syso isnt the only thing im doing in those methods To Tudor, i intend on calling them in some way like this method[0](); method[1](); method[2](); – Ploug Oct 26 '12 at 10:27
  • These things are not "obvious" to us. The more information you can supply, the better the answers will be. – Duncan Jones Oct 26 '12 at 10:32
  • Ye i see that, sorry for saying "obviously". But i intended to do alot more than just syso inside it. Anyways i had a brainfart and i realised what i could do, so i got my answer myself. I wanted to make an array of methods because in 5 methods i had 5 buffered images, But realised i could just make 1 method with a BufferedImageArray like this BufferedImage[]. Thanks anyway :) – Ploug Oct 26 '12 at 10:34
  • Are we talking about method reflection here: http://docs.oracle.com/javase/tutorial/reflect/index.html – enkor Oct 26 '12 at 10:36
  • Ok. Please answer your own question so that others know the issue is solved. Or accept Sumit's answer, which seems reasonable. – Duncan Jones Oct 26 '12 at 10:36

1 Answers1

0

No you can't create Array of method in java

But This sort of thing tends to be done with anonymous subclasses.

  1. Java - Creating an array of methods
  2. Array of function pointers in Java
Community
  • 1
  • 1
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100