ToStringUtil.java

  1. /**
  2.  *
  3.  * Copyright 2019 Florian Schmaus
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack.util;

  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.List;

  21. public class ToStringUtil {

  22.     public static Builder builderFor(Class<?> clazz) {
  23.         StringBuilder sb = new StringBuilder();
  24.         sb.append(clazz.getSimpleName()).append('(');
  25.         return new Builder(sb);
  26.     }

  27.     public static final class Builder {
  28.         private final StringBuilder sb;

  29.         private Builder(StringBuilder sb) {
  30.             this.sb = sb;
  31.         }

  32.         public Builder addValue(String name, Object value) {
  33.             if (value == null) {
  34.                 return this;
  35.             }
  36.             if (sb.charAt(sb.length() - 1) != '(') {
  37.                 sb.append(' ');
  38.             }
  39.             sb.append(name).append("='").append(value).append('\'');
  40.             return this;
  41.         }

  42.         public <V> Builder add(String name, Collection<? extends V> values, Function<?, V> toStringFunction) {
  43.             if (values.isEmpty()) {
  44.                 return this;
  45.             }

  46.             sb.append(' ').append(name).append('[');

  47.             List<String> stringValues = new ArrayList<>(values.size());
  48.             for (V value : values) {
  49.                 String valueString = toStringFunction.apply(value).toString();
  50.                 stringValues.add(valueString);
  51.             }

  52.             StringUtils.appendTo(stringValues, ", ", sb);

  53.             sb.append(']');

  54.             return this;
  55.         }

  56.         public String build() {
  57.             sb.append(')');

  58.             return sb.toString();
  59.         }
  60.     }
  61. }