我正在做一个Junit教程,遇到了正在测试的标准化函数。定义如下:
public static String normalizeWord(String word) { try { int i; Class<?> normalizerClass = Class.forName("java.text.Normalizer"); Class<?> normalizerFormClass = null; Class<?>[] nestedClasses = normalizerClass.getDeclaredClasses(); for (i = 0; i < nestedClasses.length; i++) { Class<?> nestedClass = nestedClasses[i]; if (nestedClass.getName().equals("java.text.Normalizer$Form")) { normalizerFormClass = nestedClass; } } assert normalizerFormClass.isEnum(); Method methodNormalize = normalizerClass.getDeclaredMethod( "normalize", CharSequence.class, normalizerFormClass); Object nfcNormalization = null; Object[] constants = normalizerFormClass.getEnumConstants(); for (i = 0; i < constants.length; i++) { Object constant = constants[i]; if (constant.toString().equals("NFC")) { nfcNormalization = constant; } } return (String) methodNormalize.invoke(null, word, nfcNormalization); } catch (Exception ex) { return null; } }
此功能如何工作?它实际上在做什么?
它与以下功能相同:
import java.text.Normalizer; try { return Normalizer.normalize(word, Normalizer.Form.NFC); } catch (Exception ex) { return null; }
除了所有操作都是通过反射执行的。