Last active
September 26, 2015 07:39
-
-
Save searover/67ac0c71ce8313bd867f to your computer and use it in GitHub Desktop.
Using parameterized advice to count how many times a track is played
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package soundsystem; | |
import java.util.HashMap; | |
import java.util.Map; | |
import org.aspectj.lang.annotation.Aspect; | |
import org.aspectj.lang.annotation.Before; | |
import org.aspectj.lang.annotation.Pointcut; | |
@Aspect | |
public class TrackCounter{ | |
private Map<Integer, Integer> trackCounts = new HashMap<Integer, Integer>(); | |
/** | |
* The thing to focus on is the args(trackNumber) qualifier in the pointcut expression. | |
* This indicates that any int argument that is passed into the execution of playTrack() | |
* should also be passed into the advice. The parametername, trackNumber, also matches | |
* the parameter in the pointcut method signature. | |
*/ | |
@Pointcut("execution(* soundsystem.CompactDisc.playTrack(int)) and args(trackNumber)") | |
public void trackPlayed(int trackNumber){} | |
@Before("trackPlayed(trackNumber") | |
public void countTrack(int trackNumber){ | |
int currentCount = getPlayCount(trackNumber); | |
trackCounts.put(trackNumber, currentCount + 1); | |
} | |
public int getPlayCount(int trackNumber){ | |
return trackCounts.containsKey(trackNumber) ? trackCounts.get(trackNumber) : 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment