gpt4 book ai didi

java - 处理类的 RunTimeExceptions

转载 作者:行者123 更新时间:2023-11-29 06:20:05 25 4
gpt4 key购买 nike

我有一个扩展 Application 的类,它有很多方法,例如:

public User getUser(String name);
public List<User> getFriends(User user);
public List<Game> getGames(User user);

它包装了一个服务类。

这里要注意的是,如果我的设备上没有互联网,任何方法都不起作用。因此,例如我正在做的:

public User getUser(String name) {
User ret = null;
try {
return myService.getUser(name);
} catch (NoInternetException e) {
NoInternetToast.show(this);
}

return ret;
}

有没有办法包装每个调用,这样我就不必在我的 Application 的每个方法上添加 try catch?

最佳答案

如果不使用 Android 上可能提供的任何第三方库,就没有简单的方法来包装类的方法。如果您可以将应用程序功能提取到界面中,则可以使用 java.lang.reflect.Proxy实现您的接口(interface) - 代理实现是调用您的实际实现方法并缓存和处理异常的单个方法。

如果将代码分解为单独的类和接口(interface)对您来说是一种可行的方法,我可以提供更多详细信息。

编辑:这是详细信息:

您当前正在使用实现这些方法的myService。如果您还没有,请创建一个声明服务方法的接口(interface) UserService:

public interface UserService {
User getUser(String name);
List<User> getFriends(User user);
List<Game> getGames(User user);
}

并在您现有的 MyService 类上声明此接口(interface),

class MyService implements UserService {
// .. existing methods unchanged
// interface implemented since methods were already present
}

为了避免重复,异常处理被实现为 InvocationHandler

class HandleNoInternet implements InvocationHandler {
private final Object delegate; // set fields from constructor args
private final Application app;

public HandleNoInternet(Application app, Object delegate) {
this.app = app;
this.delegate = delegate;
}
public Object invoke(Object proxy, Method method, Object[] args) {
try {
// invoke the method on the delegate and handle the exception
method.invoke(delegate, args);
} catch (Exception ex) {
if ( ex.getCause() instanceof NoInternetException ) {
NoInternetToast.show(app);
} else {
throw new RuntimeException(ex);
}
}
}
}

然后在您的应用程序类中将其用作代理:

InvocationHandler handler = new HandleNoInternet(this, myService);
UserService appUserService = (UserService)Proxy.newProxyInstance(
getClass().getClassLoader(), new Class[] { UserService.class }, handler);

然后您可以使用 appUserService 而无需担心捕获 NoInternetException。

关于java - 处理类的 RunTimeExceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3478615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com