Repast / repast.simphony

Git repository for Repast Simphony development
repast.github.io
90 stars 21 forks source link

static variable can't be watched #13

Closed miaoxu9999 closed 6 years ago

miaoxu9999 commented 6 years ago

Every time when I try to use an annotation @watch listen static variable, there is an java.lang.reflect.InvocationTargetExceptionexception,

public class Zombie {
private    static Integer count = new Integer(0);

public void infect() {
        GridPoint pt = grid.getLocation(this);
        List<Object> humans = new ArrayList<Object>();
        for (Object obj : grid.getObjectsAt(pt.getX(), pt.getY())) {
            if (obj instanceof Human) {
                humans.add(obj);
            }
        }

        if (humans.size() > 0) {
            int index = RandomHelper.nextIntFromTo(0, humans.size() - 1);
            Object obj = humans.get(index);
            NdPoint spacePt = space.getLocation(obj);
            Context<Object> context = ContextUtils.getContext(obj);
            context.remove(obj);
            Zombie zombie = new Zombie(space, grid);
            System.out.println(count);
            count = count + 1;
            context.add(zombie);
            space.moveTo(zombie, spacePt.getX(), spacePt.getY());
            grid.moveTo(zombie, pt.getX(), pt.getY());

            Network<Object> net = (Network<Object>)context.getProjection("infection network");
            net.addEdge(this, zombie);
        }
    }

    public int getCount() {
        return count;
    }
}

Human.class

@Watch(watcheeClassName = "jzombies.Zombie", watcheeFieldNames = "count",
            whenToTrigger = WatcherTriggerSchedule.IMMEDIATE, triggerCondition = "$watchee.getCount() > 1")
    public void Number() {
        System.out.println("count value"  );
    }
ncollier commented 6 years ago

Unfortunately, the part of the watcher mechanism that uses reflection is not implemented to work with static fields and so you get that error. I think you could work around this by making a single instance of a class (e.g. Count) with a count field in it. Pass every Zombie a reference the single instance of that class and have the zombies change the count in that class. The Humans could then watch Count.count.

miaoxu9999 commented 6 years ago

@ncollier Thanks for your reply. I got it