我有一个与 JAVA 中的 String.format 相关的问题。 我的 HibernateDao 类负责持久化实体,并在发生任何约束违规时抛出异常。该消息包含一个 %s 并将用作上层的格式,因为我应该担心这一层中的类型,因此无法识别我无法持久化的对象。
public Entity persistEntity(Entity entity) {
if (entity == null || StringUtils.isBlank(entity.getId()))
throw new InternalError(CANNOT_INSERT_NULL_ENTITY);
try {
getHibernateTemplate().save(entity);
} catch (DataAccessException e) {
if (e.getCause() instanceof ConstraintViolationException)
throw new HibernateDaoException("%s could not be persisted. Constraint violation.");
throw new HibernateDaoException(e);
}
return entity;
}
然后在我的 DaoHelper 类中,我将捕获此异常并抛出一个新异常,并带有格式化消息。
//Correct Code
public Entity create(Entity object) throws MyException {
try {
return this.hibernateDao.persistEntity(object);
} catch (HibernateDaoException he) {
String format = he.getMessage();
throw new MyException(String.format(format,object.getClass().getSimpleName()));
}
}
我的问题是,为什么我不能在 String.format 方法中直接调用 he.getMessage() ?并且必须使用“tmp”变量...它只是不会替换字符串中的 %s。
//What I wished to do, but I cant.
public Entity create(Entity object) throws MyException {
try {
return this.hibernateDao.persistEntity(object);
} catch (HibernateDaoException he) {
throw new MyException(String.format(he.getMessage(),object.getClass().getSimpleName()));
}
}
提前致谢。
最佳答案
这应该关闭,因为预期的行为正在发挥作用。正如 @Kal 和 @highlycaffelated 评论的那样,直接调用 getMessage() 确实有效,我的构建肯定发生了一些事情并且没有正确更新。不过,这些消息现在确实显示正确。 感谢您的快速解答:)
关于java - String.format 使用 exception.getMessage() 作为格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7016578/