To define a generic method, add a generic parameter, or list of generic parameters before the method’s return value:
public <T> void printType(T x) { // etc...
public <A, B, C> void printThreeTypes(A x, B y, C z) { // etc...
With class parametrisation, you need to specify the parameter type when you instantiate the class, but with generic methods, you can let the compiler figure it out, which I believe is called type argument inference.
The code below demonstrates Generic Method usage:
public class PrintType {
public <T> void printType(T x) { // etc...
System.out.println(x.getClass().getSimpleName());
}
/**
* Demonstrate how to write a method with more than one parameter type.
*/
public <A, B, C> void printThreeTypes(A x, B y, C z) { // etc...
System.out.println("Type 1: " + x.getClass().getSimpleName() + " Type 2: "
+ y.getClass().getSimpleName() + " Type 3: " + z.getClass().getSimpleName());
}
public static void main(String[] args) {
PrintType instance = new PrintType();
instance.printType("Hello");
// this will autobox
instance.printType(1);
// this will autobox
instance.printType(1.0);
instance.printType('c');
instance.printType(instance);
instance.printThreeTypes("Hello", 'C', instance);
}
}
The output from this code is:
String
Integer
Double
Character
PrintType
Type 1: String Type 2: Character Type 3: PrintType
No comments:
Post a comment