我必须使用以下代码在我的 struts 2 应用程序操作类方法中设置private InputStream responseMsg
responseMsg = new ByteArrayInputStream(message.getBytes("UTF-8"));
在这种情况下,我必须处理 UnsupportedEncodingException
检查异常。我想在这么多操作方法中分配InputStream
,如果我在所有方法中添加throws UnsupportedEncodingException
,意味着代码看起来很困惑。所以我决定在实用程序类中创建实用程序方法
public class Utilities {
public InputStream responseMessage(String message) throws UnsupportedEncodingException {
return new ByteArrayInputStream(message.getBytes("UTF-8"));
}
}
从我的 Action 类调用
responseMsg = new Utilities().responseMessage(message);
在这种情况下,还会出现编译时错误来处理操作方法中的UnsupportedEncodingException
,帮助我为所有操作类方法创建实用程序方法。
最佳答案
如果您正在谈论"UTF-8"
具体来说,推荐的方法是抛出 Error
如果某些必须按规范工作的东西不能工作。例如
public InputStream responseMessage(String message) {
try {
return new ByteArrayInputStream(message.getBytes("UTF-8"));
} catch(UnsupportedEncodingException ex) {
throw new AssertionError("Every JVM must support UTF-8", ex);
}
}
由于 Java 7 live 对于这种特定情况要容易得多:
public InputStream responseMessage(String message) {
return new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
}
如果涉及任意字符集,您应该处理可能的异常,这不是什么大问题,因为您的代码使用返回的 InputStream
将不得不处理声明的 IOException
无论如何,UnsupportedEncodingException
是 IOException
的子类。所以需要catch
或throws
IOException
的条款将涵盖UnsupportedEncodingException
已经。
关于java - 如何创建一个已检查异常的实用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24999656/