Mixin in Java with Aspects – for a Scala traits sample

Scala traits allow new behaviors to be mixed into a class. Consider two traits to add auditing and version related fields to JPA entities:

package mvcsample.domain

import javax.persistence.Version
import scala.reflect.BeanProperty
import java.util.Date

trait Versionable {
  var version: Int = _

trait Auditable {
  var createdAt: Date = _

  var updatedAt: Date = _

Now to mix in ‘Versionable’ and ‘Auditable’ with their fields and behavior in a Member entity:

@Table(name = 'members')
class Member(f: String, l: String) extends BaseDomain with Auditable with Versionable {

  def this() = this(null, null)

  var first: String = f

  var last: String = l

  @OneToMany(fetch = FetchType.EAGER, mappedBy = 'member')
  var addresses: java.util.List[Address] = _

trait BaseDomain {
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = 'id')
  var id: Long = 0

The Member class above will now have the behavior of the BaseDomain class, and will have the behavior of Versionable trait and the Auditable trait. This kind of mixin is not possible with plain Java, as the equivalent of traits with fields and behavior would be an abstract(or concrete) class and Java allows deriving only from 1 base class. However with AspectJ it is possible to achieve an equivalent of mixin. Consider the following aspects defined using Aspectj language:

package mvcsample.aspect;

import javax.persistence.Column;
import javax.persistence.Version;
import mvcsample.annot.Versioned;

public interface Versionable {

    static aspect VersionableAspect {
        declare parents: @Versioned  mvcsample.domain.* implements Versionable;

        @Column(name = 'version')
        private Integer Versionable.version;    

        public Integer Versionable.getVersion() {
        return this.version;

        public void Versionable.setVersion(Integer version) { 
        this.version = version;

package mvcsample.aspect;

import java.util.Date;
import javax.persistence.Column;

import mvcsample.annot.Audited;
public interface Auditable {
    static aspect AuditableAspect {
        declare parents: @Audited mvcsample.domain.* implements Auditable ;

        private Date Auditable.createdAt;

        private Date Auditable.updatedAt;

        public Date Auditable.getCreatedAt(){
            return this.createdAt;

        public void Auditable.setCreatedAt(Date createdAt) {
            this.createdAt = createdAt;

        public Date Auditable.getUpdatedAt(){
            return this.updatedAt;

        public void Auditable.setUpdatedAt(Date updatedAt) {
            this.updatedAt = updatedAt;

‘declare parents: @Versioned mvcsample.domain.* implements Versionable;’ aspectj construct adds ‘Versionable’ interface as a parent to any class in package ‘mvcsampple.domain’ annotated with @Versioned, similarly the one for ‘Auditable’. Then the aspect goes about adding fields to the Versionable interface which in turn ends up adding(mixing in) the fields to the targeted entity classes, this way the Audit related and Version related fields and methods get mixed into the entity classes. With these two aspects defined, a target entity class would look like this:

public class Member extends BaseDomain{
 public Member(){}
 public Member(String first, String last){
  this.first = first;
  this.last = last;
 private String first;
 private String last;
 @OneToMany(fetch=FetchType.EAGER, mappedBy="member")
 private List<address>addresses = new ArrayList<>();

The fields and behavior defined in the Versionable and Auditable aspects would be mixed into this entity(more generally into any entity with @Versioned and @Audited annotations). Probably not as clean as Scala traits but works nicely.

Reference: Mixin in Java with Aspects – for a Scala traits sample from our JCG partner Biju Kunjummen at the all and sundry blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply

9 + = twelve

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: