根据你的我的意见的答案,你将不能够只用注释来做到这一点。你可以,当然,创建注释和创建将检测然后一些反射代码并执行一些代码,但是这不会改变你的代码太多,因为你将需要调用parser
方法,你打电话给你的方法,我认为前这对你不会太有帮助,因为在每次调用之前你都需要调用解析器方法。
如果你需要,你提到的行为(自动呼叫),你需要向你的注解与像春天(普通Java)还是AspectJ(AspectJ的代码)一些AOP框架结合起来。随着时间的推移,你可以设置切入点,每次到达这个点时,都可以执行一些代码。您可以配置然后在方法执行之前和/或之后执行一些代码。
如果第一种情形是足够的,你可以这样做:
记录仪:枚举
public enum Logger {
INFO,
DEBUG;
}
LogMethodCall:注释
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) // the annotation will be available during runtime
@Target(ElementType.METHOD) // this can just used in methods
public @interface LogMethodCall {
Logger logLevel() default Logger.INFO;
}
人:注解类
public class Person {
// will use the default log level (INFO)
@LogMethodCall
public void foo(int a) {
System.out.println("foo! " + a);
}
@LogMethodCall(logLevel = Logger.DEBUG)
public void bar(int b) {
System.out.println("bar! " + b);
}
}
的Utils:用代码类来测试注释处理
public class AnnotationProcessing {
public static void main(String[] args) {
Person p = new Person();
Utils.log(p, "foo");
p.foo(2);
Utils.log(p, "bar");
p.bar(3);
}
}
:与日志静态方法类(这将执行 “解析”)
public class Utils {
public static void log(Object o, String methodName) {
// gets the object class
Class klass = o.getClass();
// iterate over its methods
for (Method m : klass.getMethods()) {
// verify if the method is the wanted one
if (m.getName().equals(methodName)) {
// yes, it is
// so, iterate over its annotations
for (Annotation a : m.getAnnotations()) {
// verify if it is a LogMethodCall annotation
if (a instanceof LogMethodCall) {
// yes, it is
// so, cast it
LogMethodCall lmc = (LogMethodCall) a;
// verify the log level
switch (lmc.logLevel()) {
case INFO:
System.out.println("performing info log for \"" + m.getName() + "\" method");
break;
case DEBUG:
System.out.println("performing debug log for \"" + m.getName() + "\" method");
break;
}
}
}
// method encountered, so the loop can be break
break;
}
}
}
}
AnnotationProcessing
当然,你将需要提高我的代码,以满足您的需求。这只是一个起点。
更多关于注解:
进一步了解AOP:
你想运行方法之前调试代码? – davidbuzatto
在这种情况下是的。 – SiB
好的。我忘了问。这个“之前”的执行需要在每个方法调用之前执行? – davidbuzatto