public class CastingGenericDTO<T> implements Serializable {
private T object;
public void setObject(T obj){
this.object = obj;
}
public T getObject(){
return object;
}
}
public class GenericSample{
public static void main(String args[]){
GenericSample sample = new GenericSample();
sample.checkGenericDTO();
}
public void checkGenericDTO(){
CastingGenericDTO<String> dto1 = new CastingGenericDTO<String>();
dto1.setObject(new String());
CastingGenericDTO<StringBuffer> dto2 = new CastingGenericDTO<StringBuffer>();
dto2.setObject(new StringBuffer());
CastingGenericDTO<StringBuilder> dto3 = new CastingGenericDTO<StringBuilder>();
dto3.setObject(new StringBuilder());
String temp1 = dto1.getObject();
StringBuffer temp2 = dto2.getObject();
StringBuilder temp3 = dto3.getObject();
}
}
public class Car {
protected String name;
public Car(String name){
this.name = name;
}
public String toString(){
return "Car name = " + name;
}
}
public class Bus extends Car {
public Bus(String name){
super(name);
}
public String toString(){
return "Bus name = " + name;
}
}
public class WildcardGeneric<W>{
W wildcard;
public void setWildcard(W wildcard){
this.wildcard = wildcard;
}
public W getWildcard(){
return wildcard;
}
}
public class CardWildcardSample{
public static void main(String args[]){
CardWildcardSample sample = new CardWildcardSample();
sample.callBoundedWildcardMethod();
}
public void callBoundedWildcardMethod(){
WildcardGeneric<Car> wildcard = new WildcardGeneric<Car>();
wildcard.setWildcard(new Car("Mustang"));
boundedWildcardMethod(wildcard);
}
public void boundedWildcardMethod(WildcardGeneric<? extends Car> c){
Car value = c.getWildcard();
System.out.println(value);
}
}
출력값
Car name=Mustang
public class GenericWildcardSample{
public static void main(String args[]){
GenericWildcardSample sample = new GenericWildcardSample();
callGenericMethod();
}
public <T> void genericMethod(WildcardGeneric<T> c, T addValue){
c.setWildcard(addValue);
T value = c.getWildcard();
System.out.println(value);
}
public void callGenericMethod(){
WildcardGeneric<String> wildcard = new WildcardGeneric<String>();
genericMethod(wildcard,"Data");
}
}
출력값
Data
다음과 같은 구조도 사용 가능하다.
- public void boundedGenericMethod(WildcardGeneric C,T addValue)
- public <S,T extends Car> void
multiGenericMethod(WildcardGeneric c,T addValue,S another)