Synthetic methods are often referred to as bridge methods in Java generics world. These methods are created by the Java compiler as a result of type erasure when the signature of the inherited methods change when a type extends or implements parameterized classes or interfaces. The compiler generates synthetic methods in subtypes of parameterized supertypes to make sure that subtyping works as expected.

For instance, let us try to extend the Lock interface defined in concurrency package and define an extended lock method which takes a type parameter. We use the hidden “-XD-printflat” compiler option to generate the java files after type erasure.

javac -d tmp -XD-printflat LockExImpl.java

LockEx interface

public interface LockEx extends java.util.concurrent.locks.Lock {
  //extended lock method
  void lockEx(T t);
}

LockExImpl Before Erasure

final class LockExImpl<T> extends java.util.concurrent.locks.ReentrantLock
			implements LockEx<LockExImpl>  {
  public void lockEx(LockExImpl mutex) {
    throw new UnsupportedOperationException("Not supported yet.");
  }
}

LockExImpl After Erasure

final class LockExImpl extends java.util.concurrent.locks.ReentrantLock
                                     implements LockEx {
  LockExImpl() {
    super();
  }

  public void lockEx(LockExImpl mutex) {
    throw new UnsupportedOperationException("Not supported yet.");
  }

  /*synthetic*/

  public void lockEx(Object x0) {
    this.lockEx((LockExImpl)x0);
  }
}

Possibly Related Posts:


Categories: Java

Arul

I am currently employed with Flux Corporation, Houston. This blog does not reflect the position or opinion of my employer. I'll blog my experience with things I'm fascinated with software and programming.

3 Comments

becomingguru · August 22, 2008 at 9:14 am

Hey, you have an error. Bridge and synthetic methods are not the same thing. Bridge methods are related to generics. Synthetic methods are related to surrounding class member scope.

admin · August 22, 2008 at 8:28 pm

The term “synthetic” is more of a compiler specific instruction and in this post, I refer to this term in the generics context.

You can refer the Generics FAQ for more specific details.

As per JLS section 13.1, “Any constructs introduced by the compiler that do not have a corresponding construct in the source code must be marked as synthetic, except for default constructors and the class initialization method.”

In JLS section 15.12.4.5, the implementation of bridge methods are discussed.

Hope this helps.

-Arul

Java’s Synthetic Methods | September 24th | The Shishir Kumar Blog · October 20, 2010 at 1:59 am

[…] this blog post, I look at the concept of Java synthetic methods. The post summarizes what a Java synthetic method is, how one can be created and identified, and […]

Comments are closed.