Skip to content

generic-methods

generic-methods (泛型方法) refer to methods that introduce their own type parameters, independent of the type parameters defined by their enclosing class or interface^[600-developer__java__java-base__Generics.md].

This feature allows a method to utilize generics specifically for its own logic, operations, or return type, distinct from the generic types of the class it belongs to^[600-developer__java__java-base__Generics.md].

Syntax and Implementation

A generic method is defined by declaring a type parameter within the method signature, typically placed before the return type^[600-developer__java__java-base__Generics.md].

Code Example

The following example illustrates a generic method showKeyName defined within a generic class Generic. Note that the method introduces a type parameter U which is distinct from the class's type parameter T^[600-developer__java__java-base__Generics.md].

class Generic<T> {
    T key;

    public T getKey() {
        return key;
    }

    public <U extends Number> U showKeyName(Generic<U> [container](<./container.md>)) {
        System.out.println("[container](<./container.md>) key :" + [container](<./container.md>).getKey());
        U test = [container](<./container.md>).getKey();
        return test;
    }
}

In this example, <U extends Number> declares U as a type parameter restricted to Number types, allowing the method to accept a Generic container of a specific numeric type independent of what T is^[600-developer__java__java-base__Generics.md].

  • [[Generics]]
  • [[23种经典设计模式]] (Often utilizes generics for flexible structure creation)
  • Bounded Type Parameters

Sources

^[600-developer__java__java-base__Generics.md]