Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [aspectj-users] Was my aspect implementation overriden?

Eyon wrote:

> I have created an aspect with inter-type method
> declarations for classes that implement an interface. 
> Now some of the classes that use this interface will
> override the implementation provided by the aspect.  

> At runtime, is there a way to ask an instance whether
> it overrode the method provided in the aspect?  I just
> need to know this within the aspect that provided the
> method!

There is no straightforward way to do this. Java reflection just sees
that the class of the object has the method, and it appears as if it
was directly declared in the class. However, if you are using AspectJ
5, this might be the first good use case I know of for the Java 5
design that annotations on methods are *not* inherited.

When bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=98901 is fixed
(currently pending verification and integration of the attached
patch), you will be able to write the following:

public interface AnInterface {} 

public aspect ITDsOnInterface { 
    
    @Retention(RetentionPolicy.RUNTIME) 
    @interface DefaultImplementation {} 
    
    @DefaultImplementation 
    public int AnInterface.getMagicNumber() { 
        return 27; 
    } 
    
    public boolean isUsingDefaultImpl(AnInterface obj) { 
        try { 
            return obj.getClass() 
                        .getDeclaredMethod("getMagicNumber") 
                        .isAnnotationPresent(DefaultImplementation.class); 
        } catch (NoSuchMethodException nsmEx) { 
            System.out.println("bang"); 
            return false; 
        } 
    } 
} 

public class ClassAcquiringDefaultImplementation implements AnInterface {} 

public class ClassProvidingCustomImplementation implements AnInterface { 
    public int getMagicNumber() { 
        return 99; 
    } 
} 

public class DefaultImplementationOrNot { 

    public static void main(String[] args) { 
        ClassAcquiringDefaultImplementation obj1 = 
            new ClassAcquiringDefaultImplementation(); 
        
        ClassProvidingCustomImplementation obj2 = 
            new ClassProvidingCustomImplementation(); 
        
        System.out.println("default impl returns: " + obj1.getMagicNumber()); 
        System.out.println("custom impl returns: " + obj2.getMagicNumber()); 
        
        System.out.println("isUsingDefaultImpl(obj1) returns " + 
                           
ITDsOnInterface.aspectOf().isUsingDefaultImpl(obj1));
        System.out.println("isUsingDefaultImpl(obj2) returns " + 
                           
ITDsOnInterface.aspectOf().isUsingDefaultImpl(obj2));
     } 

} 

-- Adrian
adrian.colyer@xxxxxxxxx


Back to the top