Function Object in Java

后端 未结 5 770
醉话见心
醉话见心 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:10

    Yes, this is easy in a functional programming language.. in Java it's a little more complex but you can work out something like this, using also generics types when possible:

    public class TestCase {
        static interface Transformable {};
    
        static class Person implements Transformable {
            Person(String name, int age) {
                this.name = name;
                this.age = age;
            }
    
            public String name;
            public int age;
        }
    
        static interface Modifier {
            void modify(Transformable object);
        }
    
        static class AgeIncrementer implements Modifier {
            public void modify(Transformable p) {
                ++((Person)p).age;
            }
        }
    
        static void applyOnList(List objects, Modifier modifier) {    
            for (Transformable o : objects) {
                modifier.modify(o);
            }
        }
    
        public static void main(String[] args) {
            ArrayList l = new ArrayList();
            l.add(new Person("John", 10));
            l.add(new Person("Paul", 22));
            l.add(new Person("Frank", 35));
    
            applyOnList(l, new AgeIncrementer());
    
            for (Person p : l)
                System.out.println(p.age);
        }
    }
    

提交回复
热议问题