深入aspectj之introduction

本文中主要包含aspectj introduction demo。

例如下面的一个类Product:

/** * */ package aop.aspectj.introduction; /** * 这是一个测试类,主要是来测试不通过修改源代码的形式 * 来实现对这个类新增加一个功能. * @author jefferyxu * */ public class Product { private String productId; private String name; private String description; private int price; /** * @return the productId */ public String getProductId() { return productId; } /** * @param productId the productId to set */ public void setProductId(String productId) { this.productId = productId; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the price */ public int getPrice() { return price; } /** * @param price the price to set */ public void setPrice(int price) { this.price = price; } }

如果想要给这个类增加一个属性或者是方法的话,最简单方法就是修改代码,但是这么做不得不面临代码的重新测试,那么如何解决?答案之一就是使用aspectj的introduction性质。具体做法如下:

IValidatable.java :

/** * */ package aop.aspectj.introduction; /** * @author jefferyxu * */ public interface IValidatable { boolean isOnSale(); }

ProductValidatableAspect.java

/** * @author jefferyxu */ package aop.aspectj.introduction; public aspect ProductValidatableAspect { /** * 使用aspectj的特性,不改变product的源代码,而对这个 * 类新增加一个新的功能 */ declare parents: Product extends IValidatable; public boolean Product.isOnSale() { return this.getPrice() > 0 ? true : false; } }

客户端可以这么使用这个类了,就好像这个类中存在了一个方法isOnSale方法:

/** * */ package aop.aspectj.introduction; /** * @author jefferyxu * */ public class TestProduct { public static void main(String[] args) { Product product = new Product(); product.setPrice(10); System.out.println(((IValidatable)product).isOnSale()); } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值