下面列出了org.springframework.util.ClassUtils#getShortName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Generate the actual URL paths for the given controller class.
* <p>Subclasses may choose to customize the paths that are generated
* by overriding this method.
* @param beanClass the controller bean class to generate a mapping for
* @return the URL path mappings for the given controller
*/
protected String[] generatePathMappings(Class<?> beanClass) {
StringBuilder pathMapping = buildPathPrefix(beanClass);
String className = ClassUtils.getShortName(beanClass);
String path = (className.endsWith(CONTROLLER_SUFFIX) ?
className.substring(0, className.lastIndexOf(CONTROLLER_SUFFIX)) : className);
if (path.length() > 0) {
if (this.caseSensitive) {
pathMapping.append(path.substring(0, 1).toLowerCase()).append(path.substring(1));
}
else {
pathMapping.append(path.toLowerCase());
}
}
if (isMultiActionControllerType(beanClass)) {
return new String[] {pathMapping.toString(), pathMapping.toString() + "/*"};
}
else {
return new String[] {pathMapping.toString() + "*"};
}
}
@Test
public void testUnqualifiedFileNameNotFound() throws Exception {
PropertyEditor fileEditor = new FileEditor();
String fileName = ClassUtils.classPackageAsResourcePath(getClass()) + "/" + ClassUtils.getShortName(getClass())
+ ".clazz";
fileEditor.setAsText(fileName);
Object value = fileEditor.getValue();
assertTrue(value instanceof File);
File file = (File) value;
assertFalse(file.exists());
String absolutePath = file.getAbsolutePath();
if (File.separatorChar == '\\') {
absolutePath = absolutePath.replace('\\', '/');
}
assertTrue(absolutePath.endsWith(fileName));
}
@Test
public void testUnqualifiedPathNameFound() throws Exception {
PropertyEditor pathEditor = new PathEditor();
String fileName = ClassUtils.classPackageAsResourcePath(getClass()) + "/" +
ClassUtils.getShortName(getClass()) + ".class";
pathEditor.setAsText(fileName);
Object value = pathEditor.getValue();
assertTrue(value instanceof Path);
Path path = (Path) value;
File file = path.toFile();
assertTrue(file.exists());
String absolutePath = file.getAbsolutePath();
if (File.separatorChar == '\\') {
absolutePath = absolutePath.replace('\\', '/');
}
assertTrue(absolutePath.endsWith(fileName));
}
private Object transformAndUnmarshal(Source source, @Nullable String encoding) throws IOException {
try {
Transformer transformer = this.transformerFactory.newTransformer();
if (encoding != null) {
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
}
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
transformer.transform(source, new StreamResult(os));
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
return unmarshalInputStream(is);
}
catch (TransformerException ex) {
throw new MarshallingFailureException(
"Could not transform from [" + ClassUtils.getShortName(source.getClass()) + "]", ex);
}
}
@Test
public void testGetAsTextReturnsNullByDefault() throws Exception {
assertNull(new InputStreamEditor().getAsText());
String resource = "classpath:" + ClassUtils.classPackageAsResourcePath(getClass()) +
"/" + ClassUtils.getShortName(getClass()) + ".class";
InputStreamEditor editor = new InputStreamEditor();
editor.setAsText(resource);
assertNull(editor.getAsText());
}
@Override
public String style(@Nullable Object value) {
if (value == null) {
return NULL;
}
else if (value instanceof String) {
return "\'" + value + "\'";
}
else if (value instanceof Class) {
return ClassUtils.getShortName((Class<?>) value);
}
else if (value instanceof Method) {
Method method = (Method) value;
return method.getName() + "@" + ClassUtils.getShortName(method.getDeclaringClass());
}
else if (value instanceof Map) {
return style((Map<?, ?>) value);
}
else if (value instanceof Map.Entry) {
return style((Map.Entry<? ,?>) value);
}
else if (value instanceof Collection) {
return style((Collection<?>) value);
}
else if (value.getClass().isArray()) {
return styleArray(ObjectUtils.toObjectArray(value));
}
else {
return String.valueOf(value);
}
}
@Override
public String style(Object value) {
if (value == null) {
return NULL;
}
else if (value instanceof String) {
return "\'" + value + "\'";
}
else if (value instanceof Class) {
return ClassUtils.getShortName((Class<?>) value);
}
else if (value instanceof Method) {
Method method = (Method) value;
return method.getName() + "@" + ClassUtils.getShortName(method.getDeclaringClass());
}
else if (value instanceof Map) {
return style((Map<?, ?>) value);
}
else if (value instanceof Map.Entry) {
return style((Map.Entry<? ,?>) value);
}
else if (value instanceof Collection) {
return style((Collection<?>) value);
}
else if (value.getClass().isArray()) {
return styleArray(ObjectUtils.toObjectArray(value));
}
else {
return String.valueOf(value);
}
}
private void logNonMatchingType(C callback, ClassCastException ex) {
if (this.logger.isDebugEnabled()) {
Class<?> expectedType = ResolvableType.forClass(this.callbackType).resolveGeneric();
String expectedTypeName = (expectedType != null) ? ClassUtils.getShortName(expectedType) + " type"
: "type";
String message = "Non-matching " + expectedTypeName + " for callback "
+ ClassUtils.getShortName(this.callbackType) + ": " + callback;
this.logger.debug(message, ex);
}
}
private String getEntityName(Class<?> entityClass) {
String shortName = ClassUtils.getShortName(entityClass);
int lastDot = shortName.lastIndexOf('.');
if (lastDot != -1) {
return shortName.substring(lastDot + 1);
}
else {
return shortName;
}
}
private void transformAndMarshal(Object graph, Result result) throws IOException {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
marshalOutputStream(graph, os);
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
Transformer transformer = this.transformerFactory.newTransformer();
transformer.transform(new StreamSource(is), result);
}
catch (TransformerException ex) {
throw new MarshallingFailureException(
"Could not transform to [" + ClassUtils.getShortName(result.getClass()) + "]", ex);
}
}
@Test
public void testUnqualifiedFileNameNotFound() throws Exception {
PropertyEditor fileEditor = new FileEditor();
String fileName = ClassUtils.classPackageAsResourcePath(getClass()) + "/" +
ClassUtils.getShortName(getClass()) + ".clazz";
fileEditor.setAsText(fileName);
Object value = fileEditor.getValue();
assertTrue(value instanceof File);
File file = (File) value;
assertFalse(file.exists());
String absolutePath = file.getAbsolutePath().replace('\\', '/');
assertTrue(absolutePath.endsWith(fileName));
}
@ExceptionHandler
public String handleException(IllegalStateException ex) {
return "BasePackageTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass());
}
@ExceptionHandler(IOException.class)
public String handleIOException(IOException ex, PortletRequest request) {
return "X:" + ClassUtils.getShortName(ex.getClass());
}
/**
* Determine the conventional variable name for the return type of the given
* method, taking the generic collection type, if any, into account, falling
* back on the given return value if the method declaration is not specific
* enough, e.g. {@code Object} return type or untyped collection.
* <p>As of 5.0 this method supports reactive types:<br>
* {@code Mono<com.myapp.Product>} becomes {@code "productMono"}<br>
* {@code Flux<com.myapp.MyProduct>} becomes {@code "myProductFlux"}<br>
* {@code Observable<com.myapp.MyProduct>} becomes {@code "myProductObservable"}<br>
* @param method the method to generate a variable name for
* @param resolvedType the resolved return type of the method
* @param value the return value (may be {@code null} if not available)
* @return the generated variable name
*/
public static String getVariableNameForReturnType(Method method, Class<?> resolvedType, @Nullable Object value) {
Assert.notNull(method, "Method must not be null");
if (Object.class == resolvedType) {
if (value == null) {
throw new IllegalArgumentException(
"Cannot generate variable name for an Object return type with null value");
}
return getVariableName(value);
}
Class<?> valueClass;
boolean pluralize = false;
String reactiveSuffix = "";
if (resolvedType.isArray()) {
valueClass = resolvedType.getComponentType();
pluralize = true;
}
else if (Collection.class.isAssignableFrom(resolvedType)) {
valueClass = ResolvableType.forMethodReturnType(method).asCollection().resolveGeneric();
if (valueClass == null) {
if (!(value instanceof Collection)) {
throw new IllegalArgumentException("Cannot generate variable name " +
"for non-typed Collection return type and a non-Collection value");
}
Collection<?> collection = (Collection<?>) value;
if (collection.isEmpty()) {
throw new IllegalArgumentException("Cannot generate variable name " +
"for non-typed Collection return type and an empty Collection value");
}
Object valueToCheck = peekAhead(collection);
valueClass = getClassForValue(valueToCheck);
}
pluralize = true;
}
else {
valueClass = resolvedType;
ReactiveAdapterRegistry reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance();
if (reactiveAdapterRegistry.hasAdapters()) {
ReactiveAdapter adapter = reactiveAdapterRegistry.getAdapter(valueClass);
if (adapter != null && !adapter.getDescriptor().isNoValue()) {
reactiveSuffix = ClassUtils.getShortName(valueClass);
valueClass = ResolvableType.forMethodReturnType(method).getGeneric().toClass();
}
}
}
String name = ClassUtils.getShortNameAsProperty(valueClass);
return (pluralize ? pluralize(name) : name + reactiveSuffix);
}
@ExceptionHandler({BindException.class, IllegalArgumentException.class})
public String handle1(Exception ex, HttpServletRequest request, HttpServletResponse response)
throws IOException {
return ClassUtils.getShortName(ex.getClass());
}
@ExceptionHandler
public String handle2(IllegalArgumentException ex) {
return ClassUtils.getShortName(ex.getClass());
}
@ExceptionHandler({IllegalStateException.class, IllegalAccessException.class})
@ResponseBody
public String handleException(Exception ex) {
return "AnotherTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass());
}
/**
* Reschedule the given task object immediately.
* <p>To be implemented by subclasses if they ever call
* {@code rescheduleTaskIfNecessary}.
* This implementation throws an UnsupportedOperationException.
* @param task the task object to reschedule
* @see #rescheduleTaskIfNecessary
*/
protected void doRescheduleTask(Object task) {
throw new UnsupportedOperationException(
ClassUtils.getShortName(getClass()) + " does not support rescheduling of tasks");
}
/**
* Return a short name for this exporter.
* Used for tracing of remote invocations.
* <p>Default is the unqualified class name (without package).
* Can be overridden in subclasses.
* @see #getProxyForService
* @see RemoteInvocationTraceInterceptor
* @see org.springframework.util.ClassUtils#getShortName
*/
protected String getExporterName() {
return ClassUtils.getShortName(getClass());
}
/**
* Get the class short name. Strips the outer class name in case of an inner
* class.
*
* @param clazz
* @see org.springframework.util.ClassUtils#getShortName(Class)
* @return
*/
protected static String getShortClassName(Class<?> clazz) {
String shortName = ClassUtils.getShortName(clazz);
int dotIndex = shortName.lastIndexOf('.');
return (dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName);
}