Java Pass Method as Parameter

后端 未结 16 1028
滥情空心
滥情空心 2020-11-22 02:17

I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.

I\'ve

16条回答
  •  别那么骄傲
    2020-11-22 02:55

    Last time I checked, Java is not capable of natively doing what you want; you have to use 'work-arounds' to get around such limitations. As far as I see it, interfaces ARE an alternative, but not a good alternative. Perhaps whoever told you that was meaning something like this:

    public interface ComponentMethod {
      public abstract void PerfromMethod(Container c);
    }
    
    public class ChangeColor implements ComponentMethod {
      @Override
      public void PerfromMethod(Container c) {
        // do color change stuff
      }
    }
    
    public class ChangeSize implements ComponentMethod {
      @Override
      public void PerfromMethod(Container c) {
        // do color change stuff
      }
    }
    
    public void setAllComponents(Component[] myComponentArray, ComponentMethod myMethod) {
        for (Component leaf : myComponentArray) {
            if (leaf instanceof Container) { //recursive call if Container
                Container node = (Container) leaf;
                setAllComponents(node.getComponents(), myMethod);
            } //end if node
            myMethod.PerfromMethod(leaf);
        } //end looping through components
    }
    

    Which you'd then invoke with:

    setAllComponents(this.getComponents(), new ChangeColor());
    setAllComponents(this.getComponents(), new ChangeSize());
    

提交回复
热议问题