本章节说明了如何使用静态横切技术,以静态方式使用AspectJ中的方面把行为和接口引入现有的类中。使用这些技术,可以扩展类来实现接口,从新的父类扩展类,引入新方法和属性,减轻说发生异常的影响,以及继承多个基类。
一.扩展现有的类
package  com.aspectj;

public  aspect ExtendClassRecipe  {
    
private int MyClass.newVariable = 20;
    
    
public int MyClass.bar(String name) 
        System.out.println(
"In bar(String name) , name:" + name);
        
return this.newVariable; 
    }

}

 
        示例中将属性newVariable和方法bar(String)添加到了MyClass类中。

二.声明类之间的继承关系
    使用declare parents语句,指定特定的类是从另一个类扩展而来。
    以下代码说明了如何为MyClass类指定新的继承关系
package  com.aspectj;

public  aspect IntroduceInheritanceRecipe  {
    declare parents:MyClass 
extends AnotherClass;
}

三.使用方面实现接口
    使用declare parents语句,指定特定的类实现特定的接口。
package  com.aspectj;

public  aspect ImplementInterfaceRecipe  {
    declare parents:MyClass 
implements MyInterface;
}
    把接口应用于现有类的能力允许通过接口类型的引用那个类的对象,如:
// Create an instance of MyClass
MyInterface myObject  =   new  MyClass();
//
// Work with the interface reference
myObject.foo( 1 , " Russ " );

四.声明默认的接口实现
package  com.aspectj;

public  aspect DefaultInterfaceImplementationRecipe  {
    declare parents:MyClass 
implements MyInterface;

    
//public void MyInterface.bar(String name) {
        
//System.out.println("bar(String) called on " + this);
    
//}
}

五.减轻异常的影响
    使用declare soft语句,可以指定一组应该减轻其影响的异常--也就是说,在通过特定连接点选择的连接点上引发这些异常时,将其转换成未捕获的异常。
    示例中说明了减轻在void foo()方法上引发的ExcepionA异常的影响,使得该方法的用户不必关心如何处理这个异常。
package  com.aspectj;

public  aspect SoftExceptionRecipe  {
    pointcut callPointCut() : call(
void MyClass.foo());
    declare soft : ExceptionA : callPointCut();
}

六.扩展编译
分别使用declare error或declare warning语句,指定应该引发编译器错误或警告的条件。
示例说明了如何声明一个新的错误和警告,如果在正在编译的应用程序内发现指定的条件,编译器就会引发该错误或警告。
package  com.aspectj;

public  aspect CompilaionAdviceRecipe  {
    declare error:call(
void ProtectedAccessClass.setValue(int))  : "Must only set the ProtectedAccessClass.value from a MyClass object";
    
    declare warning:call(
void ProtectedAccessClass.getValue()) :"Should only be reading ProtectedAccessClass.value from a MyClass object";
}