What is the isSynthetic() method in Java?

Synthetic constructs in java

Synthetic constructs are classes, fields, methods and so on that are created by the Java compiler. They do not directly correspond to something in the source code.

The isSynthetic() method

The isSynthetic() method in Java checks whether a class is synthetic or no.

Syntax

The syntax for the method is as follows:

public boolean isSynthetic()

Parameters

The method doesn’t take any parameters.

Return value

This method returns a boolean. If the class is synthetic, it returns true. Otherwise, it returns false.

Example

import java.lang.reflect.Method;
public class Main{
public static void example1(){
System.out.println(Main.class + " is synthetic - " + Main.class.isSynthetic());
}
public static void example2(){
System.out.println(((Runnable) () -> {}).getClass().isSynthetic());
}
public static void example3(){
Class<Integer> integerClass = Integer.class;
Method[] methods = integerClass.getMethods();
System.out.println("Synthetic methods of Arrays class are as follows:");
for (Method method : methods) {
if (method.isSynthetic()) {
System.out.println("Method: " + method.getName());
}
}
}
public static void main(String[] args) {
example1();
example2();
example3();
}
}

Explanation

  • Lines 5–7: We define the example1() method, where we check if the Main class is synthetic or not using the isSynthetic() method.
  • Lines 9–11: We define the example2() method, where we check if the Runnable class is synthetic or not using isSynthetic() method.
  • Lines 13–22: We define the example3() method, where we list all the synthetic methods of the Integer class. First, we list all the methods of the Integer class using the getMethods() method. Next, we loop through the list of methods and check each method to see if it’s synthetic or not.
  • Lines 24–28: The example1(), example2(), and example3() methods are called.

Free Resources