我有如下所示的代码,最后我已经展示了当用户将传递字符串参数时将如何调用它,他将接收字符串参数,我的问题是有人可以告诉我如何user将对象类型作为参数传递
来调用我的代码下面是界面
interface applyBuisnessRule<T> {
public T execute(String jobCode) throws Exception;
}
下面是班级
class CardvaletImpl<T> implements applyBuisnessRule<T> {
private static final String Success = null;
public T execute(String jobCode) throws Exception {
T result = null;
// put your logic and populate result here. I believe you are not going to return Success every time as it String
return result;
}
}
现在这段代码将字符串作为参数传递
CardvaletImpl<String> cardvaletImpl = new CardvaletImpl<>();
String result = cardvaletImpl.execute("JOBCODE");
请告知我如何将对象作为参数传递并获取对象作为回报,就像我在上面对字符串
的情况所做的那样另请注意我如何将下面的类也作为泛型,因为这是调用我上面的类的上下文类
public class BuisnessRuleContext {
private Object Object = null;
private applyBuisnessRule buisnessRuleName;
public void setAbr(applyBuisnessRule abr) {
this.buisnessRuleName = abr;
}
//use the strategy
public Object applyBuisnessRule(String jobcode) {
try {
Object = buisnessRuleName.execute(jobcode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Object;
}
}
答案 0 :(得分:0)
如果您希望相同类型的对象作为参数:
interface ApplyBusinessRule<T> {
public T execute(T jobCode) throws Exception;
}
*请注意更正后的界面名称。
如果您想要不同类型的对象作为参数:
interface ApplyBusinessRule<T, R> {
public R execute(T jobCode) throws Exception;
}
这类似于Java 8定义的Function
接口:
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
要了解详情,请阅读The Java™ Tutorials。