Class MoreObjects

java.lang.Object
cloud.opencode.base.core.MoreObjects

public final class MoreObjects extends Object
MoreObjects - Extended Object utilities, including toString helper 扩展对象工具类 - 包含 toString 辅助工具

This class provides additional utilities for working with objects, most notably a fluent API for building toString() implementations.

该类提供了处理对象的额外工具,最重要的是用于构建 toString() 实现的流式 API。

Features | 主要功能:

  • ToStringHelper for building readable toString() output - ToStringHelper 用于构建可读的 toString() 输出
  • Null-safe property inclusion - 空值安全的属性包含
  • Omit null values option - 可选忽略 null 值
  • Array-aware formatting - 数组感知格式化

Usage Examples | 使用示例:

// Simple usage | 简单用法
public String toString() {
    return MoreObjects.toStringHelper(this)
        .add("name", name)
        .add("age", age)
        .toString();
}
// Output: User{name=John, age=30}

// With omitNullValues | 忽略空值
return MoreObjects.toStringHelper("Person")
    .omitNullValues()
    .add("name", name)
    .add("nickname", null)  // will be omitted
    .add("age", age)
    .toString();
// Output: Person{name=John, age=30}

// Using addValue for unnamed values | 使用 addValue 添加无名值
return MoreObjects.toStringHelper("Point")
    .addValue(x)
    .addValue(y)
    .toString();
// Output: Point{10, 20}

Thread Safety | 线程安全:

ToStringHelper is NOT thread-safe. It should be used locally within a method.

ToStringHelper 非线程安全,应在方法内局部使用。

Since:
JDK 25, opencode-base-core V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • firstNonNull

      public static <T> T firstNonNull(T first, T second)
      Returns the first of two given parameters that is not null. If both are null, returns null. 返回两个参数中第一个非空的。如果都为空,返回 null。
      Type Parameters:
      T - the type of the references
      Parameters:
      first - the first reference
      second - the second reference
      Returns:
      first if it is non-null; otherwise second
    • toStringHelper

      public static MoreObjects.ToStringHelper toStringHelper(Object self)
      Creates a ToStringHelper for the given instance. The class name will be used as the prefix. 为给定实例创建 ToStringHelper。类名将用作前缀。
      Parameters:
      self - the object instance (typically "this")
      Returns:
      a new ToStringHelper instance
    • toStringHelper

      public static MoreObjects.ToStringHelper toStringHelper(Class<?> clazz)
      Creates a ToStringHelper with the given class name. 使用给定类创建 ToStringHelper。
      Parameters:
      clazz - the class whose simple name will be used
      Returns:
      a new ToStringHelper instance
    • toStringHelper

      public static MoreObjects.ToStringHelper toStringHelper(String className)
      Creates a ToStringHelper with the given string as the class name. 使用给定字符串作为类名创建 ToStringHelper。
      Parameters:
      className - the class name to use in the output
      Returns:
      a new ToStringHelper instance