List of usage examples for java.lang Class getSimpleName
public String getSimpleName()
From source file:Main.java
/** * Gets the base location of the given class. * <p>//from ww w. j a v a2s. c om * If the class is directly on the file system (e.g., * "/path/to/my/package/MyClass.class") then it will return the base directory * (e.g., "file:/path/to"). * </p> * <p> * If the class is within a JAR file (e.g., * "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the * path to the JAR (e.g., "file:/path/to/my-jar.jar"). * </p> * * @param c The class whose location is desired. * @see FileUtils#urlToFile(URL) to convert the result to a {@link File}. */ public static URL getLocation(final Class<?> c) { if (c == null) return null; // could not load the class // try the easy way first try { final URL codeSourceLocation = c.getProtectionDomain().getCodeSource().getLocation(); if (codeSourceLocation != null) return codeSourceLocation; } catch (SecurityException e) { // NB: Cannot access protection domain. } catch (NullPointerException e) { // NB: Protection domain or code source is null. } // NB: The easy way failed, so we try the hard way. We ask for the class // itself as a resource, then strip the class's path from the URL string, // leaving the base path. // get the class's raw resource path final URL classResource = c.getResource(c.getSimpleName() + ".class"); if (classResource == null) return null; // cannot find class resource final String url = classResource.toString(); final String suffix = c.getCanonicalName().replace('.', '/') + ".class"; if (!url.endsWith(suffix)) return null; // weird URL // strip the class's path from the URL string final String base = url.substring(0, url.length() - suffix.length()); String path = base; // remove the "jar:" prefix and "!/" suffix, if present if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2); try { return new URL(path); } catch (MalformedURLException e) { e.printStackTrace(); return null; } }
From source file:com.erudika.para.utils.Utils.java
/** * Returns the simple name of a class in lowercase (AKA the type). * * @param clazz a core class//ww w .j av a2 s . c om * @return just the name in lowercase or an empty string if clazz is null */ public static String type(Class<? extends ParaObject> clazz) { return (clazz == null) ? "" : clazz.getSimpleName().toLowerCase(); }
From source file:com.kth.common.utils.etc.LogUtil.java
/** ? , ?? ? ??. */ private static String getClassLineNumber(final Class<?> clazz) { StackTraceElement[] elements = Thread.currentThread().getStackTrace(); if (elements != null) { for (StackTraceElement e : elements) { if ((clazz.getName()).equals(e.getClassName()) || (clazz.getSimpleName()).equals(e.getClassName())) { return e.getClassName() + "(" + e.getMethodName() + ":" + e.getLineNumber() + ")"; }/*from w ww . j a v a 2 s .c o m*/ } } return ""; }
From source file:edu.brown.utils.ClassUtil.java
public static <T> T newInstance(Class<T> target_class, Object params[], Class<?> classes[]) { // Class<?> const_params[] = new Class<?>[params.length]; // for (int i = 0; i < params.length; i++) { // const_params[i] = params[i].getClass(); // System.err.println("[" + i + "] " + params[i] + " " + // params[i].getClass()); // } // FOR// www . ja v a2 s . co m Constructor<T> constructor = ClassUtil.getConstructor(target_class, classes); T ret = null; try { ret = constructor.newInstance(params); } catch (Exception ex) { throw new RuntimeException("Failed to create new instance of " + target_class.getSimpleName(), ex); } return (ret); }
From source file:org.toobsframework.data.beanutil.BeanMonkey.java
public static Collection populateCollection(IValidator v, String beanClazz, String indexPropertyName, Map properties, boolean validate, boolean noload) throws IllegalAccessException, InvocationTargetException, ValidationException, ClassNotFoundException, InstantiationException, PermissionException { // Do nothing unless all arguments have been specified if ((beanClazz == null) || (properties == null) || (indexPropertyName == null)) { log.warn("Proper parameters not present."); return null; }/*from ww w. j a v a2 s.c o m*/ ArrayList returnObjs = new ArrayList(); Object[] indexProperty = (Object[]) properties.get(indexPropertyName); if (indexProperty == null) { log.warn("indexProperty [" + indexProperty + "] does not exist in the map."); return returnObjs; } Class beanClass = Class.forName(beanClazz); String beanClazzName = beanClass.getSimpleName(); // beanClazz.substring(beanClazz.lastIndexOf(".") + 1); IObjectLoader odao = null; ICollectionLoader cdao = null; if (objectClass.isAssignableFrom(beanClass)) { odao = (IObjectLoader) beanFactory.getBean( Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao"); if (odao == null) { throw new InvocationTargetException(new Exception("Object DAO class " + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded")); } } else { cdao = (ICollectionLoader) beanFactory.getBean( Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao"); if (cdao == null) { throw new InvocationTargetException(new Exception("Collection DAO class " + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded")); } } boolean namespaceStrict = properties.containsKey("namespaceStrict"); for (int index = 0; index < indexProperty.length; index++) { String guid = (String) indexProperty[index]; boolean newBean = false; Object bean = null; if (!noload && guid != null && guid.length() > 0) { bean = (odao != null) ? odao.load(guid) : cdao.load(Integer.parseInt(guid)); } if (bean == null) { bean = Class.forName(beanClazz).newInstance(); newBean = true; } if (v != null) { v.prePopulate(bean, properties); } if (log.isDebugEnabled()) { log.debug("BeanMonkey.populate(" + bean + ", " + properties + ")"); } Errors e = null; if (validate) { String beanClassName = null; beanClassName = bean.getClass().getName(); beanClassName = beanClassName.substring(beanClassName.lastIndexOf(".") + 1); e = new BindException(bean, beanClassName); } String namespace = null; if (properties.containsKey("namespace") && !"".equals(properties.get("namespace"))) { namespace = (String) properties.get("namespace") + "."; } // Loop through the property name/value pairs to be set Iterator names = properties.keySet().iterator(); while (names.hasNext()) { // Identify the property name and value(s) to be assigned String name = (String) names.next(); if (name == null || (indexPropertyName.equals(name) && !noload) || (namespaceStrict && !name.startsWith(namespace))) { continue; } Object value = null; if (properties.get(name) == null) { log.warn("Property [" + name + "] does not have a value in the map."); continue; } if (properties.get(name).getClass().isArray() && index < ((Object[]) properties.get(name)).length) { value = ((Object[]) properties.get(name))[index]; } else if (properties.get(name).getClass().isArray()) { value = ((Object[]) properties.get(name))[0]; } else { value = properties.get(name); } if (namespace != null) { name = name.replace(namespace, ""); } PropertyDescriptor descriptor = null; Class type = null; // Java type of target property try { descriptor = PropertyUtils.getPropertyDescriptor(bean, name); if (descriptor == null) { continue; // Skip this property setter } } catch (NoSuchMethodException nsm) { continue; // Skip this property setter } catch (IllegalArgumentException iae) { continue; // Skip null nested property } if (descriptor.getWriteMethod() == null) { if (log.isDebugEnabled()) { log.debug("Skipping read-only property"); } continue; // Read-only, skip this property setter } type = descriptor.getPropertyType(); String className = type.getName(); try { value = evaluatePropertyValue(name, className, namespace, value, properties, bean); } catch (NoSuchMethodException nsm) { continue; } try { BeanUtils.setProperty(bean, name, value); } catch (ConversionException ce) { log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] "); if (validate) { e.rejectValue(name, name + ".conversionError", ce.getMessage()); } else { throw new ValidationException(bean, className, name, ce.getMessage()); } } catch (Exception be) { log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:" + value + "] "); if (validate) { e.rejectValue(name, name + ".error", be.getMessage()); } else { throw new ValidationException(bean, className, name, be.getMessage()); } } } /* if (newBean && cdao != null) { BeanUtils.setProperty(bean, "id", -1); } */ if (validate && e.getErrorCount() > 0) { throw new ValidationException(e); } returnObjs.add(bean); } return returnObjs; }
From source file:com.evolveum.midpoint.gui.api.util.WebModelServiceUtils.java
public static <T extends ObjectType> void deleteObject(Class<T> type, String oid, ModelExecuteOptions options, OperationResult result, PageBase page, PrismObject<UserType> principal) { LOGGER.debug("Deleting {} with oid {}, options {}", new Object[] { type.getSimpleName(), oid, options }); OperationResult subResult;//from ww w.j a va 2 s .c o m if (result != null) { subResult = result.createMinorSubresult(OPERATION_DELETE_OBJECT); } else { subResult = new OperationResult(OPERATION_DELETE_OBJECT); } try { Task task = createSimpleTask(result.getOperation(), principal, page.getTaskManager()); ObjectDelta delta = new ObjectDelta(type, ChangeType.DELETE, page.getPrismContext()); delta.setOid(oid); page.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), options, task, subResult); } catch (Exception ex) { subResult.recordFatalError("WebModelUtils.couldntDeleteObject", ex); LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete object", ex); } finally { subResult.computeStatus(); } if (result == null && WebComponentUtil.showResultInPage(subResult)) { page.showResult(subResult); } LOGGER.debug("Deleted with result {}", new Object[] { result }); }
From source file:de.alpharogroup.lang.ClassExtensions.java
/** * Returns the name of the given class or null if the given class is null. If the given flag * 'simple' is true the simple name (without the package) will be returned. * * @param clazz/*from w ww . j ava 2 s . c o m*/ * The class * @param simple * The flag if the simple name should be returned. * * @return The name of the given class or if the given flag 'simple' is true the simple name * (without the package) will be returned. */ public static String getName(Class<?> clazz, final boolean simple) { String name = null; if (clazz != null) { while (clazz.isAnonymousClass()) { clazz = clazz.getSuperclass(); } if (simple) { name = clazz.getSimpleName(); } else { name = clazz.getName(); } } return name; }
From source file:com.kegare.caveworld.util.CaveUtils.java
public static <T extends Entity> T createEntity(Class<T> clazz, World world) { try {//from w w w . j ava 2s . c om String name = String.valueOf(EntityList.classToStringMapping.get(clazz)); Entity entity = EntityList.createEntityByName(Strings.nullToEmpty(name), world); if (entity == null || entity.getClass() != clazz) { return null; } return clazz.cast(entity); } catch (Exception e) { CaveLog.warning("Failed to create entity: %s", clazz.getSimpleName()); return null; } }
From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java
/** * Logs the contents of all factories on a host. * * @param host/* w w w. ja v a 2 s . c o m*/ * @throws Throwable */ public static <H extends ServiceHost & XenonHostInfoProvider> void dumpHost(H host, String referrer) throws Throwable { logger.info(String.format("host: %s - %s", host.getId(), host.getPort())); for (Class factory : host.getFactoryServices()) { try { Operation op = Operation .createGet(UriUtils.buildExpandLinksQueryUri(UriUtils.buildUri(host, factory))); Operation result = sendRequestAndWait(host, op, referrer); logger.info(String.format("%s: %s: %s", host.getPort(), factory.getSimpleName(), Utils.toJson(false, false, result.getBodyRaw()))); } catch (Throwable ex) { logger.info(String.format("Could not get service: %s", factory.getCanonicalName())); } } }
From source file:com.cloudbees.plugins.credentials.CredentialsSelectHelper.java
/** * Returns a map of the {@link CredentialsProvider} instances keyed by their name. A provider may have more than one * entry if there are inferred unique short nicknames. * * @return a map of the {@link CredentialsProvider} instances keyed by their name * @since 2.1.1//from w w w .j av a 2 s . c o m */ public static Map<String, CredentialsProvider> getProvidersByName() { Map<String, CredentialsProvider> providerByName = new TreeMap<String, CredentialsProvider>(); for (CredentialsProvider r : ExtensionList.lookup(CredentialsProvider.class)) { providerByName.put(r.getClass().getName(), r); Class<?> clazz = r.getClass(); while (clazz != null) { String shortName = clazz.getSimpleName(); clazz = clazz.getEnclosingClass(); String simpleName = shortName.toLowerCase(Locale.ENGLISH).replaceAll("(credentials|provider|impl)*", ""); if (StringUtils.isBlank(simpleName)) continue; providerByName.put(shortName, providerByName.containsKey(shortName) ? CredentialsProvider.NONE : r); providerByName.put(simpleName, providerByName.containsKey(simpleName) ? CredentialsProvider.NONE : r); } } for (Iterator<CredentialsProvider> iterator = providerByName.values().iterator(); iterator.hasNext();) { CredentialsProvider p = iterator.next(); if (p == CredentialsProvider.NONE) { iterator.remove(); } } return providerByName; }