在Java中,使用注解(Annotation)进行计数通常涉及到自定义注解和反射机制。下面是一个简单的示例,展示如何创建一个自定义注解并在运行时通过反射机制进行计数。
首先,定义一个自定义注解@Counted
:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Counted {
}
创建一个管理类来跟踪被注解的方法调用次数:
import java.util.HashMap;
import java.util.Map;
public class CounterManager {
private static final Map<String, Integer> counterMap = new HashMap<>();
public static void increment(String methodName) {
counterMap.put(methodName, counterMap.getOrDefault(methodName, 0) + 1);
}
public static int getCount(String methodName) {
return counterMap.getOrDefault(methodName, 0);
}
}
可以使用Spring AOP或其他代理机制来拦截带有@Counted
注解的方法调用,并在调用前后进行计数。这里以Spring AOP为例:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class CountedAspect {
@Around("@annotation(Counted)")
public Object countMethodCall(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
CounterManager.increment(methodName);
return joinPoint.proceed();
}
}
在需要计数的方法上添加@Counted
注解:
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Counted
public void myMethod() {
// 方法逻辑
}
}
可以通过调用CounterManager.getCount("myMethod")
来获取方法的调用次数。
ConcurrentHashMap
等线程安全的集合类。通过上述步骤,可以在Java应用中有效地使用注解进行方法调用计数。
没有搜到相关的文章