Monday, May 10, 2010

Writing first dialectic app with hegel4j

You can download latest version of hegel4j library here http://sourceforge.net/projects/hegel4j/


1. Download and install eclipse from here http://www.eclipse.org/downloads/

2. Using update site from this page http://www.eclipse.org/ajdt/downloads/ install AJDT

3. Open eclipse, click New -> Project and select AspectJ Project


Click Next, write Hegel4jMagic in the field Project name and click Finish.

4. Right click on project. Select Build Path -> Configure Build Path. Add cglib, aspectjrt and hegel4j jars.



5. Add hegel4j jar to AspectJ build path. Right click on project. Select AspectJ Tools and select Configure AspectJ Build Path then add hegel4j jar.


6. Create insterface IOrder

public interface IOrder {

public long getPrice();

public void setPrice(long price);
public String getOrderType();
public long getTotal();
}

7. Create class Order

public class Order implements IOrder{
@Dialectic(expr=">=1000",target=VIPOrder.class)
private long price;

public long getPrice() {
return price;
}

public void setPrice(long price) {
this.price = price;
}

public Order(long price) {
super();
this.price = price;
}
public String getOrderType(){
return "simple order";
}
public long getTotal(){
return price;
}
}

8. Create class VIPOrder

public class VIPOrder implements IOrder
{
@Dialectic(expr="<1000",target=Order.class)
private long price;

public long getPrice() {
return price;
}

public void setPrice(long price) {
this.price = price;
}

public VIPOrder(long price) {
super();
this.price = price;
}
public String getOrderType(){
return "VIP order";
}

@Override
public long getTotal() {
return Double.valueOf(price*0.85).longValue();
}
}

9. Add class Main

public class Main {


public static void main(String[] args) {
Order order = new Order(154);
System.out.println(""+order.getOrderType()+" total "+order.getTotal());
order.setPrice(1200);
System.out.println(""+order.getOrderType()+" total "+order.getTotal());
order.setPrice(504);
System.out.println(""+order.getOrderType()+" total "+order.getTotal());
}
}

10. Run class Main as Java application and you will see something like this

simple order total 154
VIP order total 1020
simple order total 504



No comments: