Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring utility method to convert class to generic bean name

Tags:

java

spring

My sources have constant that is class name with lowered first letter.

Is there Spring utility method that convert class type to string with lowered first letter? This allows me safely refactor class name.

For example:

SpringXXX.defaultBeanNameYYY(MyCustomBeanFactoryProcessor.class)

should produce:

myCustomBeanFactoryProcessor
like image 299
gavenkoa Avatar asked Feb 06 '23 02:02

gavenkoa


1 Answers

Using getSimpleName string as a hint from @shi for search query I found one such implementation in spring-core/src/main/java/org/springframework/util/ClassUtils.java:

/**
 * Return the short string name of a Java class in uncapitalized JavaBeans
 * property format. Strips the outer class name in case of an inner class.
 * @param clazz the class
 * @return the short name rendered in a standard JavaBeans property format
 * @see java.beans.Introspector#decapitalize(String)
 */
public static String getShortNameAsProperty(Class<?> clazz) {
    String shortName = getShortName(clazz);
    int dotIndex = shortName.lastIndexOf(PACKAGE_SEPARATOR);
    shortName = (dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName);
    return Introspector.decapitalize(shortName);
}

Usage:

@Test
public void my() {
    String str = org.springframework.util.ClassUtils.getShortNameAsProperty(MyCustomBeanFactoryProcessor.class);
    Assert.assertEquals("myCustomBeanFactoryProcessor", str);
}
like image 134
gavenkoa Avatar answered Feb 07 '23 18:02

gavenkoa