5

Is there a simple way to intercept methods in java. I need to add an annotation to required methods so that a piece of logic gets called before going through the method.

public void verifyActivity() {
   // Asset if you are on a wrong page
}

@VerifyActivity
public void testLogin() {
   // Login for my automate test
}

@VerifyActivity
public void testSomethingElse() {
   // Test some other UI Automation stuff
}

EDIT:

The recommended guice library for android apps does not contain AOP. Is it possible to achieve this using reflection without adding any libraries?

laz
  • 28,320
  • 5
  • 53
  • 50
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • Hi @aryaxt, did you find a solution? If you did, can you share? I found a library; https://code.google.com/p/android-method-interceptor/ It is not documented and I can't understand what to do. – slhddn Jan 10 '14 at 12:39

4 Answers4

2

Guice provides easy way of implementing annotations. Check this out.

http://code.google.com/p/google-guice/wiki/AOP

http://code.google.com/p/google-guice/

Sid Malani
  • 2,078
  • 1
  • 13
  • 13
  • Thanks, I decided to use Guice, and since I am not using it directly on my android app, there shouldn't be any performance problem. – aryaxt Dec 05 '11 at 00:07
2

As sid malani said Google Guice is great for this. In general you want to read up on aspect oriented programming tutorials ... There is a nice tool called JMangler that may be of use as well

Ahmed Masud
  • 21,655
  • 3
  • 33
  • 58
0

I doubt that it can be nicely done without any 3rd party libs.

There is a library called cglib, which is capable of such things.

Basically it will create a subclass of the intercepted class at runtime. You'll be able to "override" methods by implementing an InvocationHandler, which will act as a proxy when any of the superclass methods being called.

Balazs Banyai
  • 676
  • 7
  • 10
0

You can use reflection if you've coded to interfaces through dynamic proxies.

laz
  • 28,320
  • 5
  • 53
  • 50