How to avoid using break

merdle :

I think break is here not the best solution to stop this method;

How can I stop the method, when I once set the object and entitiy manager; instead of using break;

/**
 * Convenience method for setting the given entity manager to the given
 * object via reflection.
 *
 * @param object the object whose entity manager should be set
 * @param em     the entity manager that should be set
 */
protected void setEntityManager(Object object, EntityManager em) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field f : fields) {
        if (f.getType().isAssignableFrom(EntityManager.class)) {
            f.setAccessible(true);
            try {
                f.set(object, em);
                break;
            } catch (IllegalArgumentException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
Ralf Renz :

I thought of using streams like this:

protected void setEntityManager(Object object, EntityManager em) {
    Optional<Field> f = Arrays.stream(object.getClass().getDeclaredFields())
            .filter(x -> x.getType().isAssignableFrom(EntityManager.class)).findFirst();
    if (f.isPresent()) {
        f.get().setAccessible(true);
        try {
            f.get().set(object, em);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91393&siteId=1
Recommended