|
NOTA: La traducción de esta documentación es un esfuerzo personal y voluntario, no es un documento oficial de Sun Microsystems
ni Oracle ni está patrocinado por ninguna de estas empresas. Los documentos originales (en inglés) están disponibles en:
http://java.sun.com/docs/books/tutorial/.
Dirija cualquier comentario, petición, felicitación, etc. a tutorialesjava_@RROBA_codexion.com. |
Si desea ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesita que se traduzca algĂșn capĂtulo en concreto puede realizar una donación directa mediante Paypal:
|
Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the method or constructor in which it's declared.Here we've added one generic method, named/** * This version introduces a generic method. */ public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public <U> void inspect(U u){ System.out.println("T: " + t.getClass().getName()); System.out.println("U: " + u.getClass().getName()); } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); integerBox.add(new Integer(10)); integerBox.inspect("some text"); } }inspect, that defines one type parameter, namedU. This method accepts an object and prints its type to standard output. For comparison, it also prints out the type ofT. For convenience, this class now also has amainmethod so that it can be run as an application.The output from this program is:
T: java.lang.Integer U: java.lang.StringBy passing in different types, the output will change accordingly.
A more realistic use of generic methods might be something like the following, which defines a static method that stuffs references to a single item into multiple boxes:
public static <U> void fillBoxes(U u, List<Box<U>> boxes) { for (Box<U> box : boxes) { box.add(u); } }To use this method, your code would look something like the following:Crayon red = ...; List<Box<Crayon>> crayonBoxes = ...;The complete syntax for invoking this method is:Here we've explicitly provided the type to be used asBox.<Crayon>fillBoxes(red, crayonBoxes);U, but more often than not, this can be left out and the compiler will infer the type that's needed:This feature, known as type inference, allows you to invoke a generic method as you would an ordinary method, without specifying a type between angle brackets.Box.fillBoxes(red, crayonBoxes); // compiler infers that U is Crayon