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()));
}
}
事前にThx。