
Java generics in constructor
By:
Lauri on
Jul 24th, 2012 | syntax:
Java | size: 1.20 KB | hits: 19 | expires: Never
package com.mycompany.genericissue;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author lauri
*/
public class ContainerTest {
@Test
public void testIsFineOk() {
// passing explicit byte
Container<Byte> container = new Container((byte) 1);
// all right
byte value = valueOf(container);
assertEquals(1, value);
}
@Test
public void testWhichWillFail() {
// note how value to contsructor passed. Type conversion expected to be here.
Container<Byte> container = new Container(1);
// but actually integer was allowed and so we're going to fail on next line
byte value = valueOf(container);
assertEquals(1, value);
}
private byte valueOf(Container<Byte> container) {
return container == null ? -1 : container.getItem();
}
/**
* Imaginary class with generic value to hold
*
* @param <T>
*/
private static class Container<T> {
private T item;
public Container(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
}