Skip to content

Java Generic Methods

In the Java programming language, generics are categorized into three main types: classes, interfaces, and methods.^[600-developer-java-java-base-generics.md]

Definition

A generic method is a method that introduces its own type parameters, making it independent of the type parameters defined by its enclosing class.^[600-developer-java-java-base-generics.md] This allows the method to operate on different types while maintaining type safety, even if the class itself is generic or non-generic.

Syntax

To define a generic method, a type parameter section (delimited by angle brackets < >) is placed before the method's return type.^[600-developer-java-java-base-generics.md] This section declares the type variables used within the method.

Example

The following code demonstrates a class containing a generic method named showKeyName.^[600-developer-java-java-base-generics.md]

class Generic<T> {
    T key;

    public T getKey() {
        return key;
    }

    // The generic method <U> is defined here, distinct from the class's <T>
    public <U extends Number> U showKeyName(Generic<U> container) {
        System.out.println("container key :" + container.getKey());
        U test = container.getKey();
        return test;
    }
}

In this example, the method showKeyName declares a type parameter U, which is constrained to extend the Number class.^[600-developer-java-java-base-generics.md]

  • [[Java Generics]]
  • [[Type Parameters]]

Sources

^[600-developer-java-java-base-generics.md]