Java 调用作为参数传入的方法的非静态泛型函数
我试图将2个方法合并为1个,因为它们以相同的方式处理异常。我知道在C#中,可以将函数/动作作为参数传递给其他函数。我尝试创建一个通用方法来调用函数,但似乎无法理解Java 调用作为参数传入的方法的非静态泛型函数,java,generics,java-7,Java,Generics,Java 7,我试图将2个方法合并为1个,因为它们以相同的方式处理异常。我知道在C#中,可以将函数/动作作为参数传递给其他函数。我尝试创建一个通用方法来调用函数,但似乎无法理解 public String getTheStuff(String client) { try { return extService.getProduct(client); } catch (UIException e) { notHealthy(); } catch (Host
public String getTheStuff(String client) {
try {
return extService.getProduct(client);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
public CustomType getsomeMoreStuff(String source, int offset) {
try {
return extService.getMetrics(source, offset);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
我要找的是
public T invokeExtService(Function functionToInvoke, Parameters[] params){
try {
return functionToInvoke.Invoke(params);
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
正如@LouisWasserman所说,这在Java8中会更好,但是像这样的东西(未经测试)怎么样
public T调用(可调用函数){
试一试{
返回函数.call();
}捕获(UIE例外){
不健康的;
}捕获(主机例外e){
不健康的;
}捕获(例外e){
传播(e);
}
}
公共字符串getTheStuff(最终字符串客户端){
returninvoke(newcallable()){
@凌驾
公共字符串调用(){
返回extService.getProduct(客户端);
}
});
}
公共CustomType GetSomeMoreTuff(最终字符串源、最终整数偏移){
returninvoke(newcallable()){
@凌驾
公共CustomType调用(){
返回extService.getMetrics(来源,偏移量);
}
});
}
老实说,考虑到你的方法有多短(而且它们可以更短),我不确定这样做有多值得。你可以使用反射,但是使用反射的尴尬会比现在使用这两种方法更麻烦。也就是说,您可以将
UIException
和HostException
处理组合成一个catch块:catch(UIException | HostException e){notHealthy()}
(如果是Java 8,情况会稍有不同,但您明确标记了Java 7。)@LouisWasserman是的,我们的平台仍然在Java 7上:(@shmosel我本来打算进行多重捕获,但我们最终可能会以不同的方式处理异常
public <T> T invoke(Callable<T> function) {
try {
return function.call();
} catch (UIException e) {
notHealthy();
} catch (HostException e) {
notHealthy();
} catch (Exception e) {
Throwables.propagate(e);
}
}
public String getTheStuff(final String client) {
return invoke(new Callable<String>() {
@Override
public String call() {
return extService.getProduct(client);
}
});
}
public CustomType getsomeMoreStuff(final String source, final int offset) {
return invoke(new Callable<CustomType>() {
@Override
public CustomType call() {
return extService.getMetrics(source, offset);
}
});
}