gpt4 book ai didi

java - 如何避免使用 break

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:01:14 25 4
gpt4 key购买 nike

我认为 break 不是停止此方法的最佳解决方案;

一旦我设置了对象和实体管理器,我该如何停止该方法;而不是使用 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);
}
}
}
}

最佳答案

我想像这样使用流:

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);
}
}
}

关于java - 如何避免使用 break,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51588481/

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