Skip to content

Instantly share code, notes, and snippets.

@nathanchen
Created August 14, 2012 04:56
Show Gist options
  • Select an option

  • Save nathanchen/3346387 to your computer and use it in GitHub Desktop.

Select an option

Save nathanchen/3346387 to your computer and use it in GitHub Desktop.
JAVA - 数组元素格式化输出
@visibleForTesting static String format (String template, @Nullable Object... args)
{
template = String.valueOf(template);
StringBuffer builder = new StringBuffer(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while(i < args.length)
{
int placeholderStart = template.indexOf("%s", templateStart);
if(placeholderStart == -1)
break;
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
if(i < args.length)
{
builder.append(" [");
builder.append(args[i ++]);
while(i < args.length)
{
builder.append(", ");
builder.append(args[i++]);
}
builder.append("]");
}
return builder.toString();
}
public static <T> T checkNotNull(T reference, @Nullable String errorMessageTemplate,
@Nullable Object... errorMessage)
{
if(reference == null)
throw new NullPointerException(format(errorMessageTemplate, errorMessage));
return reference;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment