Synthetic methods in Java

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.
[java]
javac -d tmp -XD-printflat LockExImpl.java
[/java]
LockEx interface
[java]
public interface LockEx extends java.util.concurrent.locks.Lock {
//extended lock method
void lockEx(T t);
}
[/java]
LockExImpl Before Erasure
[java]
final class LockExImpl<T> extends java.util.concurrent.locks.ReentrantLock
implements LockEx<LockExImpl> {
public void lockEx(LockExImpl mutex) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
[/java]
LockExImpl After Erasure
[java]
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);
}
}
[/java]

3 thoughts on “Synthetic methods in Java

  1. 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.

    Like

  2. 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

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s