2

Can I create an annotation that will make the class call

Log.e("", "")

and have the class in which the method is in's name as the first argument and the method name as the second argument?

Something like this:

public class UploaderService {

    @Debuggable
    void onUploadProductSuccess(int productServerId) {

    }


}

Logcat output:

UploaderService | onUploadProductSuccess 43

Also are there any caveats in using this in Android?

Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180

1 Answers1

1

Your question is already answered here. So in short, yes and sort of. You can create custom annotations for logging or any other purpose, but you have to implement a code that checks for annotations in classes, using reflection that is available for Android as well.

If this is important for you then you should create a proxy object that gets a service name, method + paramlist params.

Something like this:

Call:

callServiceMethod("UploaderService","onUploadProductSuccess",productServerId);

Method source:

public void callServiceMethod(String serviceName, String methodName, Object... paramList){
Object service = ;//getting the service object by name
//getting the method
Method method = service.getClass().getMethod(methodName, paramList[0].class,...);

for ( Annotation a : m.getAnnotations() ) {
// if the annotation found then write to log
}
//in the end:
method.invoke(service , paramList[0], ...);
}

in this method you can check the called service for your annotations before calls the actual method.

As you can see the method is called and the log is written, but instead of calling UploaderService.onUploadProductSuccess you have to call the method above.

Community
  • 1
  • 1
gaRos
  • 2,463
  • 6
  • 22
  • 27
  • How does callServiceMethod plug into the whole picture? How do I use reflection in this particular case to obtain the class name and the method name? Can you provide a code example? – Kaloyan Roussev May 11 '15 at 12:45
  • I updated the answer. The part where you get the service is depends on how you organize your services, it could be a simple switch or something more complicated. – gaRos May 11 '15 at 15:32
  • I just used that class as an example. I dont want to specifically log services only. I want to be able to @Annotate a method and the annotation to obtain the class and the method automatically. Is that possible – Kaloyan Roussev May 11 '15 at 16:16
  • I will award my bounty in 19 hours if this remains the most elaborate answer :) – Kaloyan Roussev May 11 '15 at 16:16
  • Ok, if you want to use it for any kind of classes you should replace the first parameter with the actual object then you don't have to "look it up". – gaRos May 12 '15 at 09:23