Skip to content

Instantly share code, notes, and snippets.

@drey7925
Created April 19, 2014 01:17
Show Gist options
  • Save drey7925/11070605 to your computer and use it in GitHub Desktop.
Save drey7925/11070605 to your computer and use it in GitHub Desktop.
Constructor references to defeat erased types
public abstract class AbstractIntConstructable {
abstract public int intResult();
protected int contained;
protected int result;
protected abstract void populate(int i);
public AbstractIntConstructable(int i){
this.populate(i);
}
}
public class Box<T extends AbstractIntConstructable> {
IIntConstructor<T> constr;
T internal;
public void setContent(int i){
internal = constr.construct(i);
}
public int getContent(){
return internal.intResult();
}
public Box(IIntConstructor<T> con){
this.constr = con;
}
public static void main(String... argv){
Box<IntDoubler> doublerBox = new Box<IntDoubler>(IntDoubler::new);
doublerBox.setContent(256);
System.out.println("Doubler "+doublerBox.getContent());
Box<IntTripler> triplerBox = new Box<IntTripler>(IntTripler::new);
triplerBox.setContent(256);
System.out.println("Tripler "+triplerBox.getContent());
}
}
public interface IIntConstructor<T extends AbstractIntConstructable> {
public T construct(int in);
}
public class IntDoubler extends AbstractIntConstructable {
private int result;
public IntDoubler(int i) {
super(i);
}
@Override
public int intResult() {
return result;
}
@Override
protected void populate(int i) {
this.result = 2 * i;
}
}
public class IntTripler extends AbstractIntConstructable {
private int result;
public IntTripler(int i) {
super(i);
}
@Override
public int intResult() {
return result;
}
@Override
protected void populate(int i) {
this.result = 3 * i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment