Example usage for java.lang Class getSimpleName

List of usage examples for java.lang Class getSimpleName

Introduction

In this page you can find the example usage for java.lang Class getSimpleName.

Prototype

public String getSimpleName() 

Source Link

Document

Returns the simple name of the underlying class as given in the source code.

Usage

From source file:Main.java

public static String parseBeanToXmlStringByJAXB(Object bean, Class clase) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(clase);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
    JAXBElement<Object> rootElement = new JAXBElement<Object>(new QName(clase.getSimpleName()), clase, bean);

    OutputStream output = new OutputStream() {

        private StringBuilder string = new StringBuilder();

        public void write(int b) throws IOException {
            this.string.append((char) b);
        }/*from www.  ja va  2  s .  c  o  m*/

        //Netbeans IDE automatically overrides this toString()
        public String toString() {
            return this.string.toString();
        }
    };

    marshaller.marshal(rootElement, output);

    return output.toString();

}

From source file:com.l2jfree.util.Introspection.java

/**
 * Returns a single line string representing a subset of this object's status. <BR>
 * <BR>/*from w  ww  . j  ava 2  s . c  om*/
 * The string consists of the simple name of the given class followed by all non-static fields
 * of that class in name = value pairs, separated with comma followed by a space and enclosed in
 * simple parenthesis. If that class does not declare any non-static fields, no parenthesis are
 * added. <BR>
 * If the given class is {@code null}, then the complete status is reported, as in
 * {@link #toString(Object)}. <BR>
 * <BR>
 * Example outputs could be:<BR>
 * <CODE>
 * SomeClass<BR>
 * SomeClass(number = 15, object = this)
 * </CODE>
 * 
 * @param o an object (of type {@code T})
 * @param c {@code Class<T>} or {@code Class<? super T>}
 * @return a textual representation of the given object
 */
public static String toString(Object o, Class<?> c) {
    if (o == null)
        return "null".intern();
    Class<?> actual = (c == null ? o.getClass() : c);
    StringBuilder sb = new StringBuilder(actual.getSimpleName());
    int open = sb.length();
    sb.append('(');
    boolean written = writeFields(actual, o, sb, null, true);
    if (c == null)
        while ((actual = actual.getSuperclass()) != null)
            if (writeFields(actual, o, sb, null, !written))
                written = true;
    if (!written)
        sb.deleteCharAt(open);
    else
        sb.append(')');
    return sb.toString();
}

From source file:net.dv8tion.jda.core.utils.JDALogger.java

/**
 * Will get the {@link org.slf4j.Logger} for the given Class
 * or create and cache a fallback logger if there is no SLF4J implementation present.
 * <p>//from   w  w w.j a  v  a2  s . c o  m
 * The fallback logger will be an instance of a slightly modified version of SLF4Js SimpleLogger.
 *
 * @param  clazz
 *         The class used for the Logger name
 *
 * @return Logger for given Class
 */
public static Logger getLog(Class<?> clazz) {
    synchronized (LOGS) {
        if (SLF4J_ENABLED)
            return LoggerFactory.getLogger(clazz);
        return LOGS.computeIfAbsent(clazz.getName(), (n) -> new SimpleLogger(clazz.getSimpleName()));
    }
}

From source file:com.expressui.core.util.StringUtil.java

/**
 * Generates CSS style names from an object's class and all its parents in class hierarchy.
 *
 * @param prefix        to prepend to style name
 * @param topLevelClass style names are only generated up to this top level class in the class hierarchical. Higher
 *                      level classes are ignored
 * @param object        object to reflectively get class from
 * @return List of style names/*from   www. j  av  a2s . c  o  m*/
 */
public static List<String> generateStyleNamesFromClassHierarchy(String prefix, Class topLevelClass,
        Object object) {
    List<String> styles = new ArrayList<String>();
    Class currentClass = object.getClass();
    while (topLevelClass.isAssignableFrom(currentClass)) {
        String simpleName = currentClass.getSimpleName();
        String style = StringUtil.hyphenateCamelCase(simpleName);
        styles.add(prefix + "-" + style);
        currentClass = currentClass.getSuperclass();
    }

    return styles;
}

From source file:com.xemantic.tadedon.guice.matcher.Annotations.java

/**
 * Check if given {@code annotationType} has {@link Retention} set to {@link RetentionPolicy#RUNTIME}.
 *
 * @param annotationType the annotation type to check.
 *//*from  w w  w. j a  v  a  2 s  . c o m*/
public static void checkForRuntimeRetention(Class<? extends Annotation> annotationType) {
    Retention retention = annotationType.getAnnotation(Retention.class);
    checkArgument(((retention != null) && (retention.value() == RetentionPolicy.RUNTIME)),
            "Annotation %s is missing RUNTIME retention", annotationType.getSimpleName());
}

From source file:com.evolveum.midpoint.testing.sanity.ModelClientUtil.java

public static QName getTypeQName(Class<? extends ObjectType> type) {
    //      QName typeQName = JAXBUtil.getTypeQName(type);
    QName typeQName = new QName(NS_COMMON, type.getSimpleName());
    return typeQName;
}

From source file:edu.usu.sdl.openstorefront.core.util.EntityUtil.java

/**
 * This will set default on the fields that are marked with a default and
 * are null// w  w  w.ja v a2s.  c om
 *
 * @param entity
 */
public static void setDefaultsOnFields(Object entity) {
    Objects.requireNonNull(entity, "Entity must not be NULL");
    List<Field> fields = getAllFields(entity.getClass());
    for (Field field : fields) {
        DefaultFieldValue defaultFieldValue = field.getAnnotation(DefaultFieldValue.class);
        if (defaultFieldValue != null) {
            field.setAccessible(true);
            try {
                if (field.get(entity) == null) {
                    String value = defaultFieldValue.value();
                    Class fieldClass = field.getType();
                    if (fieldClass.getSimpleName().equalsIgnoreCase(String.class.getSimpleName())) {
                        field.set(entity, value);
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Long.class.getSimpleName())) {
                        field.set(entity, value);
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Integer.class.getSimpleName())) {
                        field.set(entity, Integer.parseInt(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Boolean.class.getSimpleName())) {
                        field.set(entity, Convert.toBoolean(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Double.class.getSimpleName())) {
                        field.set(entity, Double.parseDouble(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Float.class.getSimpleName())) {
                        field.set(entity, Float.parseFloat(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigDecimal.class.getSimpleName())) {
                        field.set(entity, Convert.toBigDecimal(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Date.class.getSimpleName())) {
                        field.set(entity, TimeUtil.fromString(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigInteger.class.getSimpleName())) {
                        field.set(entity, new BigInteger(value));
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new OpenStorefrontRuntimeException(
                        "Unable to get value on " + entity.getClass().getName(), "Check entity passed in.");
            }
        }
    }
}

From source file:edu.usu.sdl.openstorefront.doc.EntityProcessor.java

private static EntityDocModel createEntityModel(Class entity) {
    EntityDocModel docModel = new EntityDocModel();
    docModel.setName(entity.getSimpleName());

    APIDescription description = (APIDescription) entity.getAnnotation(APIDescription.class);
    if (description != null) {
        docModel.setDescription(description.value());
    }/*from w w w  .  j  a va2s .c  o  m*/

    if (!entity.isInterface()) {
        addFields(entity, docModel);
    }

    return docModel;
}

From source file:com.autentia.common.util.ejb.EntityManagerUtils.java

/**
 * Devuelve una lista con todas as entidades de la clase <code>entityClass</code>. Ordena el resultado en funcin
 * del criterio indicado.//from ww  w .j  a  v a2  s .c  o  m
 * <p>
 * Este mtodo busca una <code>NamedQuery</code> con el nombre:
 * <code>find + transferObjectClass.getSimpleName() + All</code>, y la usa para recuperar todas las entidades. Por
 * ejmplo, si la entidad se llama <code>Foo</code>, se buscar una <code>NamedQuery</code> con el nombre
 * <code>findFooAll</code>.
 * <p>
 * Si no se encuentra una <code>NamedQuery</code> con ese nombre, se usara la consulta:
 * <code>from + transferObjectClass.getSimpleName()</code>. Por ejemplo, si la entidad se llama <code>Foo</code>, se
 * ejecutar la consulta <code>from Foo</code>.
 * 
 * @param <T> tipo de los objetos devueltos por la bsqueda.
 * @param em el {@link EntityManager} donde se va a ejecutar la consulta.
 * @param entityClass clase del EJB de entidad, del que se quieren obtener todas las entidades.
 * @param sortAttribute nombre del atributo por el que se quiere ordenar.
 * @param ascending <code>true</code> si se quiere ordenar de forma ascendente. <code>false</code> para ordenacin
 *            descendente.
 * @return lista de entidades encontradas.
 */
public static <T> List<T> find(EntityManager em, Class<T> entityClass, String sortAttribute,
        boolean ascending) {
    final String entityName = entityClass.getSimpleName();
    final String queryName = "find" + entityName + "All";

    String jpaql = EntityUtils.getQueryFromNamedQuery(entityClass, queryName);
    if (jpaql == null) {
        jpaql = "from " + entityName;
    }

    return find(em, jpaql, sortAttribute, ascending);
}

From source file:Main.java

/**
 * Returns the folder that contains a jar that contains the class
 *
 * @param aclass a class to find a jar/*from   w  w w  .  j  av a  2  s  .  com*/
 * @return
 */
public static String getJarContainingFolderPath(Class aclass) throws Exception {
    CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();

    File jarFile;

    if (codeSource.getLocation() != null) {
        jarFile = new File(codeSource.getLocation().toURI());
    } else {
        String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();

        int startIndex = path.indexOf(":") + 1;
        int endIndex = path.indexOf("!");
        if (startIndex == -1 || endIndex == -1) {
            throw new IllegalStateException(
                    "Class " + aclass.getSimpleName() + " is located not within a jar: " + path);
        }
        String jarFilePath = path.substring(startIndex, endIndex);
        jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
        jarFile = new File(jarFilePath);
    }
    return jarFile.getParentFile().getAbsolutePath();
}