Reputation: 121
In the following code snippet I need to execute some logic whenever the property myList
is accessed. Is it possible?
public class Test {
public static List<String> myList = new ArrayList();
public static void addData(){
myList.add("foo");
myList.add("bar");
}
public static void removeData(){
if(myList.size() > 0){
myList.remove(0);
}
}
public static void displayData(){
for (String data : myList) {
System.out.println("data : "+data);
}
}
public static void main(String[] args) {
addData();
displayData();
removeData();
displayData();
}
}
Upvotes: 4
Views: 494
Reputation: 1509
Your question is simple enough that I do not know if I understand it. From what you have said a very small adjustment answers it.
public class Test {
private static List<String> myList = new ArrayList();
public static void addData() {
myListAccessLogic();
myList.add("foo");
myListAccessLogic();
myList.add("bar");
}
public static void removeData() {
myListAccessLogic();
if(myList.size() > 0) {
myListAccessLogic();
myList.remove(0);
}
}
public static void displayData() {
myListAccessLogic();
for (String data : myList) {
myListAccessLogic();
System.out.println("data : "+data);
}
}
public static void main(String[] args) {
addData();
displayData();
removeData();
displayData();
}
}
Upvotes: 0
Reputation: 10203
You can weave code Before
/After
/Around
any access to your field using the following pointcuts :
@Aspect
public class TestAccessorsAspect {
@Pointcut("get(java.util.List com.sample.Test.myList)")
public void readMyList(){}
@Pointcut("set(java.util.List com.sample.Test.myList)")
public void writeMyList(){}
}
in .aj syntax, this might look like this :
public aspect TestAccessorsAspect {
pointcut readMyList() : get(java.util.List com.sample.Test.myList);
pointcut writeMyList() : set(java.util.List com.sample.Test.myList);
}
Whenever those field are accessed for reading (resp. writing), those pointcuts are going to be triggered.
Upvotes: 2