Kao
Kao

Reputation: 7364

How to check if class has methods added by aspect?

Suppose I have a simple class:

public class TestClass {
   /*...*/
}

I created an aspect which injects new method to this class:

public aspect TestAspect {
    public void TestClass.aspectMethod() {
        /*...*/
    }
} 

Now, how can I check if TestClass has method added by TestAspect in runtime?

Upvotes: 0

Views: 360

Answers (2)

kriegaex
kriegaex

Reputation: 67327

Andy's answer is the correct one, I just want to answer your follow-up question from the comment:

Duck typing is not a Java feature, but if you use ITD in order to make the class implement an interface and then have an instance of your aspect-extended class you can use instanceof MyInterface in order to determine what you need to know. Other ways (also using reflection) are also available:

Interface with the method you want to add later via ITD:

package de.scrum_master.app;

public interface MyInterface {
    void myMethod();
}

Sample driver application:

package de.scrum_master.app;

import java.lang.reflect.Type;

public class Application {
    public static void main(String[] args) {
        Application application = new Application();

        // Use an instance
        System.out.println(application instanceof MyInterface);
        System.out.println(MyInterface.class.isInstance(application));

        // Use the class
        for (Type type : Application.class.getGenericInterfaces())
            System.out.println(type);
        for (Class<?> clazz : Application.class.getInterfaces())
            System.out.println(clazz);
    }
}

Aspect:

package de.scrum_master.aspect;

import de.scrum_master.app.Application;
import de.scrum_master.app.MyInterface;

public aspect MyAspect {
    declare parents : Application implements MyInterface;

    public void Application.myMethod() {}
}

Application output:

true
true
interface de.scrum_master.app.MyInterface
interface de.scrum_master.app.MyInterface

Upvotes: 1

Andy Clement
Andy Clement

Reputation: 2560

The simplest way would be to simply reflect on the class:

TestClass.class.getDeclaredMethod("aspectMethod")

which will throw NoSuchMethodException if it isn't there. Or if you have the bytes you could use a byte code visitor to check what methods exist in the byte code - but the reflective route would be less messing around.

Upvotes: 2

Related Questions