在java中有多种方法可以处理对象不为空则返回,为空则继续的逻辑。以下是几种常见的实现方式:
1. 传统 if-else 方式
public object processobject(object obj) {
if (obj != null) {
return obj;
}
// 继续执行其他逻辑
return dosomethingelse();
}2. 三元运算符(简单条件)
public object getresult() {
object obj = getpossiblenullobject();
return obj != null ? obj : getdefaultobject();
// 或者继续执行其他逻辑
}
3. 使用 optional(java 8+ 推荐)
import java.util.optional;
public object processwithoptional() {
return optional.ofnullable(getpossiblenullobject())
.orelseget(() -> {
// 对象为空时执行的逻辑
return getdefaultvalue();
});
}
// 或者链式调用
public object processchain() {
return optional.ofnullable(getobject1())
.or(() -> optional.ofnullable(getobject2()))
.orelse(getdefaultobject());
}4. 链式空值检查
public object getfirstnonnull() {
object obj1 = getobject1();
if (obj1 != null) return obj1;
object obj2 = getobject2();
if (obj2 != null) return obj2;
object obj3 = getobject3();
if (obj3 != null) return obj3;
return getdefaultobject();
}5. 实用工具方法
public class objectutils {
public static <t> t getfirstnonnull(supplier<t>... suppliers) {
for (supplier<t> supplier : suppliers) {
t result = supplier.get();
if (result != null) {
return result;
}
}
return null;
}
// 使用示例
public void example() {
object result = getfirstnonnull(
() -> getobject1(),
() -> getobject2(),
() -> getobject3()
);
}
}6. 在 stream 中使用(java 8+)
import java.util.stream.stream;
public object getfromstream() {
return stream.of(getobject1(), getobject2(), getobject3())
.filter(obj -> obj != null)
.findfirst()
.orelse(getdefaultobject());
}7. 使用 apache commons lang 或 guava
apache commons lang:
import org.apache.commons.lang3.objectutils;
public object getwithapache() {
return objectutils.firstnonnull(
getobject1(),
getobject2(),
getobject3()
);
}google guava:
import com.google.common.base.moreobjects;
import com.google.common.base.supplier;
public object getwithguava() {
return moreobjects.firstnonnull(
getobject1(),
getobject2()
);
}实际应用示例
public class userservice {
public user finduser(string id) {
// 尝试从缓存获取
user user = cache.get(id);
if (user != null) {
return user; // 不为空则返回
}
// 缓存为空,继续从数据库获取
user = database.get(id);
if (user != null) {
cache.put(id, user); // 存入缓存
return user;
}
// 都没有找到,返回默认值
return user.anonymous;
}
// 使用 optional 的优雅写法
public user finduserelegant(string id) {
return optional.ofnullable(cache.get(id))
.or(() -> optional.ofnullable(database.get(id)))
.map(user -> {
cache.put(id, user);
return user;
})
.orelse(user.anonymous);
}
}推荐
对于简单的条件判断,使用传统 `if-else` 最直观
对于复杂的空值处理链,推荐使用 java 8+ 的 `optional`,代码更清晰
如果项目中已经有 apache commons 或 guava,可以使用它们的工具类
对于性能敏感的场景,传统 if-else 可能更快
到此这篇关于java实现处理对象不为空则返回,为空则继续的文章就介绍到这了,更多相关java处理对象不为空内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论