Don't like ads? PRO users don't see any ads ;-)
Guest

Java generics in constructor

By: Lauri on Jul 24th, 2012  |  syntax: Java  |  size: 1.20 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. package com.mycompany.genericissue;
  2.  
  3. import org.junit.Test;
  4. import static org.junit.Assert.*;
  5.  
  6. /**
  7.  *
  8.  * @author lauri
  9.  */
  10. public class ContainerTest {
  11.  
  12.     @Test
  13.     public void testIsFineOk() {
  14.         // passing explicit byte
  15.         Container<Byte> container = new Container((byte) 1);
  16.  
  17.         // all right
  18.         byte value = valueOf(container);
  19.         assertEquals(1, value);
  20.     }
  21.  
  22.     @Test
  23.     public void testWhichWillFail() {
  24.         // note how value to contsructor passed. Type conversion expected to be here.
  25.         Container<Byte> container = new Container(1);
  26.  
  27.         // but actually integer was allowed and so we're going to fail on next line
  28.         byte value = valueOf(container);
  29.         assertEquals(1, value);
  30.     }
  31.  
  32.     private byte valueOf(Container<Byte> container) {
  33.         return container == null ? -1 : container.getItem();
  34.     }
  35.  
  36.     /**
  37.      * Imaginary class with generic value to hold
  38.      *
  39.      * @param <T>
  40.      */
  41.     private static class Container<T> {
  42.  
  43.         private T item;
  44.  
  45.         public Container(T item) {
  46.             this.item = item;
  47.         }
  48.  
  49.         public T getItem() {
  50.             return item;
  51.         }
  52.     }
  53. }