Reputation: 17
When I create an instance of the class actor I add the object faction.
//Constructor
Actor(String name, Race race, Faction faction){
this.name = name;
this.race = race;
this.faction = faction;
}
I wanted that every time the object faction is used by the actor the an auto count inside the object faction increments, and every time the object actor is destroyed it decrements.
public class Faction {
private String name;
private int membersNum;
private ArrayList<Faction> knowFactionList = new ArrayList<Faction>();
private ArrayList<Relation> factionRelationList = new ArrayList<Relation>();
Faction(String name){
this.name = name;
}
public void addBattleMember(){
membersNum++;
}
public void removeBattleMember(){
membersNum--;
}
I am now using this method inside the class Faction Manager to create the list and manually decreasing when the object actor stop being used.
public void buildActiveFactionsOnBattle(ArrayList<Actor> actorList) {
for (Actor act : actorList) {
act.getFaction().addBattleMember();
if (!activeFactionsOnBattle.contains(act.getFaction()))
activeFactionsOnBattle.add(act.getFaction());
}
}
Upvotes: 1
Views: 2088
Reputation: 7887
"the best way to do that is static variable, and increment it every time that actor using faction in the constructor – Fady Saad 1 min ago"
I would go this route as its much easier.
Somewhere in the class do something such as:
static int fractionCount = 0;
Static variables are such that all instances of, for say the fraction object, reference the same variable.
Changing the static variable from one class will change the variable for all instances of that class.
Upvotes: 0
Reputation: 240898
You need to hook the logic somewhere under the user space in JVM. A native JVM agent is capable of doing it.
Refer https://github.com/JigarJoshi/jvm-objects-inspector
Upvotes: 1