Javaでの型パラメータについて書きたいと思います。
基本の型パラメータ
Sample.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Sample<T>{ private T data; public static void main(String[] args) { Sample sample = new Sample(new Hoge("name","hogehoge")); Sample sample2 = new Sample(new Foo("height",20)); } public Sample(T data){ this.data=data; } } |
Hoge.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class Hoge { private String fieldName; private String value; public Hoge(String fieldName ,String value){ this.fieldName=fieldName; this.value =value; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
Foo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public class Foo { private String fieldName; private int value; public Foo(String fieldName ,int value){ this.fieldName=fieldName; this.value =value; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } } |
型パラメータの制限(ある型を継承した場合)
実際には継承関係などで使われることが多く、型を制限することができます。
Sample.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
public class Sample<T extends Base>{ private T data; public static void main(String[] args) { Hoge hoge =new Hoge(); Foo foo = new Foo(); hoge.setFieldName("name"); hoge.setValue("hogehoge"); foo.setFieldName("height"); foo.setValue(60); Sample sample = new Sample(hoge); sample.showMessage(); //name Sample sample2 = new Sample(foo); sample2.showMessage(); //height } public Sample(T data){ this.data=data; } public void showMessage(){ //BaseにあるパラメータなのでfiledNameが使える System.out.println(this.data.getFieldName()); } } |
Base.java
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Base { private String fieldName; public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } } |
Hoge.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Hoge extends Base { private String value; public Hoge(){ } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } |
Foo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Foo extends Base { private int value; public Foo(){ } public int getValue() { return value; } public void setValue(int value) { this.value = value; } } |