intellij-idea Live Templates Insert the name of the current class


Example

Consider the utility class pattern: a class with only static methods and no fields. It's recommended to prevent instantiation of such classes by adding a private a constructor.

This live template example makes it easy to add a private constructor to an existing class, using the name of the enclosing class.

private $className$() {
    throw new AssertionError("utility class, forbidden constructor");
}

Applicable in Java: declaration scope.

configure live template

Click Edit variables to define the className variable as the built-in className() expression, and check the Skip if defined box to avoid prompting for a custom name, which is unnecessary in this example.

define className variable

For example, inside a class like this:

class ListUtils {

    // ...
}

When you type "utility_class" (the abbreviation), this will insert a constructor like this:

class ListUtils {
    private ListUtils() {
        throw new AssertionError("utility class, forbidden constructor");
    }

    // ...
}