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
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 extends Transformable> objects, Modifier extends Transformable> 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);
}
}