分析Java中的StringHelper类

前言

在项目中实战学习并记录可用的工具类

1. 概念

Java标准库(java.lang包)并没有提供名为StringHelper的类。通常,类似的字符串处理工具类并不是Java标准库的一部分,而是由程序员自行编写或者使用第三方库提供的工具类。

2. 功能示例

功能作用示例
join(Object[] array, String separator)将数组中的元素用指定的分隔符连接成一个字符串。join(new String[]{“a”, “b”, “c”}, “-”) 返回 “a-b-c”。
join(Iterable<?> iterable, String separator)将可迭代对象中的元素用指定的分隔符连接成一个字符串。join(Arrays.asList(“a”, “b”, “c”), “-”) 返回 “a-b-c”。
decapitalize(String string)将字符串的首字母转换为小写,除非字符串以多个大写字母开头示例: decapitalize(“Hello”) 返回 “hello”。
isNullOrEmptyString(String value)检查字符串是否为null或仅包含空格isNullOrEmptyString(" ") 返回 true。
toShortString(Member member)创建成员对象的紧凑字符串表示形式,用于调试或toString()方法。toShortString(someMethod) 返回方法的紧凑字符串表示。
toShortString(Type type)创建类型对象的紧凑字符串表示形式,用于调试或toString()方法toShortString(String.class) 返回 “java.lang.String”。

其他辅助方法:包括一些私有辅助方法,如startsWithSeveralUpperCaseLetters等。

实际上是一个自定义的StringHelper工具类,包含了一系列用于字符串操作的静态方法。

3. Demo示例

以下是该类中主要方法的作用和功能:

public class StringHelper {

	private static final Pattern DOT = Pattern.compile( "\\." );

	private StringHelper() {
	}

	/**
	 * Joins the elements of the given array to a string, separated by the given separator string.
	 *
	 * @param array the array to join
	 * @param separator the separator string
	 *
	 * @return a string made up of the string representations of the given array's members, separated by the given separator
	 *         string
	 */
	public static String join(Object[] array, String separator) {
		return array != null ? join( Arrays.asList( array ), separator ) : null;
	}

	/**
	 * Joins the elements of the given iterable to a string, separated by the given separator string.
	 *
	 * @param iterable the iterable to join
	 * @param separator the separator string
	 *
	 * @return a string made up of the string representations of the given iterable members, separated by the given separator
	 *         string
	 */
	public static String join(Iterable<?> iterable, String separator) {
		if ( iterable == null ) {
			return null;
		}

		StringBuilder sb = new StringBuilder();
		boolean isFirst = true;

		for ( Object object : iterable ) {
			if ( !isFirst ) {
				sb.append( separator );
			}
			else {
				isFirst = false;
			}

			sb.append( object );
		}

		return sb.toString();
	}

	/**
	 * Returns the given string, with its first letter changed to lower-case unless the string starts with more than
	 * one upper-case letter, in which case the string will be returned unaltered.
	 * <p>
	 * Provided to avoid a dependency on the {@link java.beans.Introspector} API which is not available on the Android
	 * platform (HV-779).
	 *
	 * @param string the string to decapitalize
	 *
	 * @return the given string, decapitalized. {@code null} is returned if {@code null} is passed as input; An empty
	 *         string is returned if an empty string is passed as input
	 *
	 * @see java.beans.Introspector#decapitalize(String)
	 */
	public static String decapitalize(String string) {
		if ( string == null || string.isEmpty() || startsWithSeveralUpperCaseLetters( string ) ) {
			return string;
		}
		else {
			return string.substring( 0, 1 ).toLowerCase( Locale.ROOT ) + string.substring( 1 );
		}
	}

	/**
	 * Indicates if the string is null or is empty ie only contains whitespaces.
	 *
	 * @param value the string considered
	 * @return true if the string is null or only contains whitespaces
	 */
	public static boolean isNullOrEmptyString(String value) {
		return value == null || value.trim().isEmpty();
	}

	/**
	 * Creates a compact string representation of the given member, useful for debugging or toString() methods. Package
	 * names are shortened, e.g. "org.hibernate.validator.internal.engine" becomes "o.h.v.i.e". Not to be used for
	 * user-visible log messages.
	 */
	public static String toShortString(Member member) {
		if ( member instanceof Field ) {
			return toShortString( (Field) member );
		}
		else if ( member instanceof Method ) {
			return toShortString( (Method) member );
		}
		else {
			return member.toString();
		}
	}

	private static String toShortString(Field field) {
		return toShortString( field.getGenericType() ) + " " + toShortString( field.getDeclaringClass() ) + "#" + field.getName();
	}

	private static String toShortString(Method method) {
		return toShortString( method.getGenericReturnType() ) + " " +
				method.getName() +
				Arrays.stream( method.getGenericParameterTypes() )
					.map( StringHelper::toShortString )
					.collect( Collectors.joining( ", ", "(", ")" ) );
	}

	/**
	 * Creates a compact string representation of the given type, useful for debugging or toString() methods. Package
	 * names are shortened, e.g. "org.hibernate.validator.internal.engine" becomes "o.h.v.i.e". Not to be used for
	 * user-visible log messages.
	 */
	public static String toShortString(Type type) {
		if ( type instanceof Class ) {
			return toShortString( (Class<?>) type );
		}
		else if ( type instanceof ParameterizedType ) {
			return toShortString( (ParameterizedType) type );
		}
		else {
			return type.toString();
		}
	}

	private static String toShortString(Class<?> type) {
		if ( type.isArray() ) {
			return toShortString( type.getComponentType() ) + "[]";
		}
		else if ( type.getEnclosingClass() != null ) {
			return toShortString( type.getEnclosingClass() ) + "$" + type.getSimpleName();
		}
		else if ( type.getPackage() == null ) {
			return type.getName();
		}

		return toShortString( type.getPackage() ) + "." + type.getSimpleName();
	}

	private static String toShortString(ParameterizedType parameterizedType) {
		Class<?> rawType = ReflectionHelper.getClassFromType( parameterizedType );
		if ( rawType.getPackage() == null ) {
			return parameterizedType.toString();
		}

		String typeArgumentsString = Arrays.stream( parameterizedType.getActualTypeArguments() )
			.map( t -> toShortString( t ) )
			.collect( Collectors.joining( ", ", "<", ">" ) );

		return toShortString( rawType ) + typeArgumentsString;
	}

	private static String toShortString(Package pakkage) {
		String[] packageParts = DOT.split( pakkage.getName() );

		return Arrays.stream( packageParts )
			.map( n -> n.substring( 0, 1 ) )
			.collect( Collectors.joining( "." ) );
	}

	private static boolean startsWithSeveralUpperCaseLetters(String string) {
		return string.length() > 1 &&
				Character.isUpperCase( string.charAt( 0 ) ) &&
				Character.isUpperCase( string.charAt( 1 ) );
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值