例如,我有3个子类:
public interface IPrinter{
}
public class StringPrinter implements IPrinter{
public String getInfo(String input){
return "String value:"+input;
}
}
public class IntegerPrinter implements IPrinter{
public String getInfo(Integer input){
return "Integer value:"+input.intValue();
}
}
public class BooleanPrinter implements IPrinter{
public String getInfo(Boolean input){
return "Boolean input:"+input.booleanValue();
}
}
它们是IPrinter的子项,参数是Object的子项。
在我的业务代码中,对象的调用必须放在其他一些长代码(例如:loops或if-else)之间,以获得不同类型的不同值,每次我必须复制并粘贴代码,例如:
for(a){
if(b){
result=new StringPrinter().getInfo("abc");
}
}
for(a){
if(b){
result=new IntegerPrinter().getInfo(new Integer(123));
}
}
for(a){
if(b){
result=new BooleanPrinter().getInfo(new Boolean(true));
}
}
现在我想要一个可以自动调用哪个魔术函数,例如:
public static void main(String[] args){
result=magicGetInfo<StringPrinter,String>(new StringPrinter(),"abc");
}
public static String magicGetInfo(IPrinter p,Object o){
for(a){
if(b){
//magic code, may be using template
}
}
}
有没有办法做到这一点?我试过了:
public class StringPrinter implements IPrinter{
public String getInfo(String input){
return "String value:"+input;
}
}
public interface IPrinter {
<Input extends Object> String getInfo(Input input);
}
public static <P extends IPrinter,I extends Object> String getInfo(P p,I i,Class<? extends P> c){
try{
return ((IPrinter)c.newInstance()).getInfo(i);
}catch (Exception e){
}
}
但是StringPrinter无法编译:
class 'StringPrinter' must either be declared abstract or implement abstract method