AppSensei
AppSensei

Reputation: 8400

How to I pass a String and Object using Custom Annotations in Java

Is there a way to pass values through the @LogMethod annotation. I want to pass a String and an Object (DataFileVO). How Can I do it?

Something like this.

@LogMethod(logLevel = LoggerOne.DEBUG, duaNum = "23L", duaDataFile = myListObject)

LoggerOne.java

public enum LoggerOne {
    INFO, DEBUG;
}

LogMethod.java

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogMethod {
   LoggerOne logLevel() default LoggerOne.INFO;
 }

Util.java

public class Util {

public static void log(Object o, String methodName) {
    Class klass = o.getClass();

    for (Method m : klass.getMethods()) {
        if (m.getName().equals(methodName)) {
            for (Annotation a : m.getAnnotations()) {
                if (a instanceof LogMethod) {
                    LogMethod lm = (LogMethod) a;
                    switch (lm.logLevel()) {
                      case INFO:
                        System.out.println("Performing Custom INFO logging for " + m.getName());
                        break;
                      case DEBUG:
                        System.out.println("Performing Custom DEBUG logging for " + m.getName());
                    }
                }
            }
            break;
        }
    }
   }
 }

DataFileDaoImpl.java

    @LogMethod(logLevel = LoggerOne.DEBUG)
public List<DuaDataFileVO> getDuaByDuaAndShipperCode(String duaNum, Long shipperCode) {
     List<DuaDataFileVO> list = new ArrayList<DuaDataFileVO>();
     // Some code
        return list;
}

Upvotes: 0

Views: 5546

Answers (1)

Uwe Schmidt
Uwe Schmidt

Reputation: 81

Annotations are only 'metadata' and not part of the concrete program. So, if you're compile a program, the metadata will not exist any more.

Read Lesson: Annotations - ORACLE for more informations.

I think you can solve your problem with 'Aspect-oriented programming'. Here is a Tutorial Java Method Logging with AOP and Annotations.

The following code comes from this tutorial.

The important code is the aspect:

@Aspect
public class MethodLogger {
  @Around("execution(* *(..)) && @annotation(Loggable)")
  public Object around(ProceedingJoinPoint point) {
    long start = System.currentTimeMillis();
    Object result = point.proceed();
    Logger.info(
      "#%s(%s): %s in %[msec]s",
      MethodSignature.class.cast(point.getSignature()).getMethod().getName(),
      point.getArgs(),
      result,
      System.currentTimeMillis() - start
    );
    return result;
  }
}

This aspect is working around an execution (method) - which has any modifier, any name and any arguments - that is annotated with @Loggable. The MethodLogger prints a 'Info' with the classpath, method-name, arguments, the result and the execution-time from the executed method.

You can use this annotation like this:

public class Foo {
  @Loggable
  public int power(int x, int p) {
    return Math.pow(x, p);
  }
}

With this example-output:

[INFO] com.example.Foo #power(2, 10): 1024 in 12μs

You need this dependencies to compile:

<dependency>
    <groupId>com.jcabi</groupId>
    <artifactId>jcabi-aspects</artifactId>
</dependency>

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
</dependency>

The tutorial is very hepful. To unsterstand why it works, read it completely.

I hope it helps you.

Upvotes: 4

Related Questions