Function Object in Java

后端 未结 5 760
醉话见心
醉话见心 2021-02-03 11:32

I wanna implement a javascript like method in java , is this possible ?

Say , I have a Person class :

public class Person {
 private String name ;
 priva         


        
5条回答
  •  别跟我提以往
    2021-02-03 12:07

    You can do it with an interface and an anonymous inner class implementing it, like

    Person p1 = new Person("Jenny",20);
    Person p2 = new Person("Kate",22);
    List pList = Arrays.asList(p1, p2);
    
    interface Operation {
      abstract void execute(Person p);
    }
    
    public void modList(List list, Operation op) {
      for (Person p : list)
        op.execute(p);
    }
    
    modList(pList, new Operation {
      public void execute(Person p) { p.setAge(p.getAge() + 1)};
    });
    

    Note that with varargs in Java5, the call to Arrays.asList can be simplified as shown above.

    Update: A generified version of the above:

    interface Operation {
      abstract void execute(E elem);
    }
    
    public  void modList(List list, Operation op) {
      for (E elem : list)
        op.execute(elem);
    }
    
    modList(pList, new Operation() {
        public void execute(Person p) { p.setAge(p.getAge() + 1); }
    });
    

    Note that with the above definition of modList, you can execute an Operation on e.g. a List too (provided Student is a subclass of Person). A plain List parameter type would not allow this.

提交回复
热议问题