Example usage for java.lang Class toString

List of usage examples for java.lang Class toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Converts the object to a string.

Usage

From source file:egovframework.rte.bat.core.reflection.EgovReflectionSupport.java

/**
 * VO? Field Setter Method? ? Map? Put .
 * Bean ?    ?./*from w  w  w . ja v  a  2 s .co m*/
 */
public void generateSetterMethodMap(Class<?> type, String[] names) throws Exception {
    methods = type.newInstance().getClass().getMethods();
    methodMap = new HashMap<String, Method>();

    for (int i = 0; i < names.length; i++) {
        try {
            String strMethod = "set" + (names[i].substring(0, 1)).toUpperCase() + names[i].substring(1);
            methodMap.put(names[i], retrieveMethod(methods, strMethod));
        } catch (Exception e) {
            throw new Exception("Cannot create a method list of given : " + type.toString());
        }
    }
}

From source file:org.formix.dsx.serialization.XmlSerializer.java

/**
 * Deserialize an XML tree into the given type.
 * /*from  w  w w. j a  va  2  s .c  om*/
 * @param root
 *            The XML root element.
 * 
 * @param type
 *            The type of the desired object.
 * 
 * @param <T>
 *            The infered type for the parameter {code type}.
 * 
 * @return a deserialized object from the given XML.
 * 
 * @throws XmlException
 *             Thrown when a problem occurs during deserialization.
 */
public <T> T deserialize(XmlElement root, Class<T> type) throws XmlException {

    if (type.toString().equals("class [B")) {
        @SuppressWarnings("unchecked")
        T value = (T) Base64.decodeBase64(root.getChild(0).toString());
        return value;
    }

    // If the type is a base type from java.util or java.sql or is a
    // collection then decode it directly.
    if (type.getName().startsWith("java.") || Collection.class.isAssignableFrom(type)) {
        @SuppressWarnings("unchecked")
        T value = (T) this.getValue(root, type, null, null);
        return value;
    }

    String rootName = this.capitalize(root.getName());

    String childName = "";
    XmlElement childElem = null;
    if (root.getChild(0) instanceof XmlElement) {
        childElem = (XmlElement) root.getChild(0);
        childName = this.capitalize(childElem.getName());
        if (rootName.equals(childName))
            return this.deserialize(childElem, type);
    }

    T target;
    try {
        target = type.newInstance();
    } catch (Exception e) {
        throw new XmlException("Unable to instanciate type " + type.getName(), e);
    }

    this.onBeforeDeserialization(new SerializationEvent(this, root, target));

    SortedMap<String, Method> methods = this.createMethodMap(type);
    for (XmlContent content : root.getChilds()) {
        if (content instanceof XmlElement) {

            XmlElement elem = (XmlElement) content;
            String methodName = "set" + this.capitalize(elem.getName());
            String signature = methods.tailMap(methodName).firstKey();

            // If the setter is not found for the specified methodName, skip
            // this setter.
            if (signature.startsWith(methodName)) {

                Method setMethod = methods.get(signature);

                Class<?> paramType = setMethod.getParameterTypes()[0];
                try {
                    Object value = this.getValue(elem, paramType, methods, target);
                    setMethod.invoke(target, new Object[] { value });
                } catch (Exception e) {
                    String msg = String.format(
                            "Unable to assign the XMLElement %s to" + " the property [%s.%s] (%s)", elem,
                            type.getName(), setMethod.getName(), signature);
                    throw new XmlException(msg, e);
                }

            } else {
                throw new XmlException(String.format("Unable to find the method %s.", methodName));
            }
        }
    }

    this.onAfterDeserialization(new SerializationEvent(this, root, target));

    return target;
}

From source file:org.energyos.espi.common.repositories.jpa.ResourceRepositoryImpl.java

@SuppressWarnings("unchecked")
@Override/*  w  w  w.j a  v a2s  .c o  m*/
public <T extends IdentifiedObject> List<Long> findAllIds(Class<T> clazz) {
    try {
        String queryFindById = (String) clazz.getDeclaredField("QUERY_FIND_ALL_IDS").get(String.class);

        return em.createNamedQuery(queryFindById).getResultList();
    } catch (NoSuchFieldException | IllegalAccessException e) {
        System.out.printf("**** FindAllIds Exception: %s - %s\n", clazz.toString(), e.toString());
        throw new RuntimeException(e);
    }
}

From source file:org.jboss.windup.config.RuleSubset.java

/**
 * Logs the time taken by this rule and adds this to the total time taken for this phase
 *///w  w  w  . jav  a2  s. co m
private void logTimeTakenByPhase(GraphContext graphContext, Class<? extends RulePhase> phase, int timeTaken) {
    if (!timeTakenByPhase.containsKey(phase)) {
        RulePhaseExecutionStatisticsModel model = new GraphService<>(graphContext,
                RulePhaseExecutionStatisticsModel.class).create();
        model.setRulePhase(phase.toString());
        model.setTimeTaken(timeTaken);
        model.setOrderExecuted(timeTakenByPhase.size());
        timeTakenByPhase.put(phase, model.asVertex().getId());
    } else {
        GraphService<RulePhaseExecutionStatisticsModel> service = new GraphService<>(graphContext,
                RulePhaseExecutionStatisticsModel.class);
        RulePhaseExecutionStatisticsModel model = service.getById(timeTakenByPhase.get(phase));
        int prevTimeTaken = model.getTimeTaken();
        model.setTimeTaken(prevTimeTaken + timeTaken);
    }
}

From source file:org.force66.beantester.tests.ToStringTest.java

@Override
public boolean testBeanClass(Class<?> klass, Object[] constructorArgs) {
    this.setFailureReason(null);
    Object instance1 = InstantiationUtils.safeNewInstance(klass, constructorArgs);
    try {//w  w w  .  j a  v a2  s  .c o  m
        if (instance1.toString() == null) {
            this.setFailureReason(
                    "toString() equals null; a favorite pit test plug to see if toString() is being tested properly");
            return false;
        }

        //  Testing if toString() excepts if fields have values....
        InjectionUtils.injectValues(instance1, valueGeneratorFactory, false);
        instance1.toString();
        return true;
    } catch (Exception e) {
        throw new BeanTesterException("toString() failed execution", e).addContextValue("bean class",
                klass.toString());
    }
}

From source file:org.energyos.espi.common.repositories.jpa.ResourceRepositoryImpl.java

@SuppressWarnings("unchecked")
@Override/*from   ww  w. jav a  2s .c  om*/
public <T extends IdentifiedObject> T findById(Long id, Class<T> clazz) {
    try {
        String queryFindById = (String) clazz.getDeclaredField("QUERY_FIND_BY_ID").get(String.class);

        return (T) em.createNamedQuery(queryFindById).setParameter("id", id).getSingleResult();
    } catch (NoSuchFieldException | IllegalAccessException e) {
        System.out.printf("**** FindbyId(Long id) Exception: %s - %s id: %s\n", clazz.toString(), e.toString(),
                id);
        throw new RuntimeException(e);
    }

}

From source file:net.fenyo.gnetwatch.targets.Target.java

/**
 * Returns events from the first BEFORE begin (or at begin) to the last AFTER end (or at end).
 * @param begin start time.//  w  ww  .  j  a  v a  2 s  . c  om
 * @param end end time.
 * @param clazz type of events.
 * @return List<EventGeneric> list of selected events.
 */
// AWT thread
// lock survey: synchro << sync_tree << HERE
//              sync_value_per_vinterval << sync_update << synchro << sync_tree << HERE
public List<EventGeneric> getEvents(final Date begin, final Date end, Class clazz) {
    final List<EventGeneric> selected_events = new LinkedList<EventGeneric>();

    final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession();
    session.beginTransaction();

    try {
        // get events inside the range
        // j'ai eu a ici et plus loin : Illegal attempt to associate a collection with two open sessions
        session.update(this);
        final EventList el = eventLists.get(clazz.toString());

        java.util.List results = session
                .createQuery("from EventGeneric as ev where ev.eventList = :event_list "
                        + "and ev.date >= :start_date and ev.date <= :stop_date " + "order by ev.date asc")
                .setString("event_list", el.getId().toString())
                .setString("start_date", new java.sql.Timestamp(begin.getTime()).toString())
                .setString("stop_date", new java.sql.Timestamp(end.getTime()).toString()).list();

        for (final EventGeneric event : (java.util.List<EventGeneric>) results)
            selected_events.add(event);

        // get event just before the beginning of the range
        results = session
                .createQuery("from EventGeneric as ev where ev.eventList = :event_list "
                        + "and ev.date < :start_date " + "order by ev.date desc")
                .setString("event_list", el.getId().toString())
                .setString("start_date", new java.sql.Timestamp(begin.getTime()).toString()).list();
        if (results.size() >= 1)
            selected_events.add(0, (EventGeneric) results.get(0));

        // get event just after the last of the range
        results = session
                .createQuery("from EventGeneric as ev where ev.eventList = :event_list "
                        + "and ev.date > :stop_date " + "order by ev.date asc")
                .setString("event_list", el.getId().toString())
                .setString("stop_date", new java.sql.Timestamp(end.getTime()).toString()).list();
        if (results.size() >= 1)
            selected_events.add((EventGeneric) results.get(0));

        session.getTransaction().commit();
    } catch (final Exception ex) {
        log.error("Exception", ex);
        session.getTransaction().rollback();
    }

    return selected_events;
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java

@Test
public void testGenerateJavaCode01() throws ClassNotFoundException, IllegalAccessException,
        InstantiationException, NoSuchMethodException, InvocationTargetException {
    String code = this.generator.generateJavaCode(null, "TestGenerateJavaCode01", null, null,
            "public final String testMethod01(String concatenate)", "concatenate + \" some other cool text.\"");

    assertNotNull("The code should not be null.", code);
    assertTrue("The code should have length.", code.length() > 0);
    assertEquals("The code is not correct.",
            "public final class TestGenerateJavaCode01\r\n" + "{\r\n"
                    + "\tpublic final String testMethod01(String concatenate)\r\n" + "\t{\r\n"
                    + "\t\treturn concatenate + \" some other cool text.\";\r\n" + "\t}\r\n" + "}",
            code);//w  ww. ja  va  2  s  .co m

    JavaFileManager compiled = this.compileClass("TestGenerateJavaCode01", code);

    Class<?> classObject = compiled.getClassLoader(null).loadClass("TestGenerateJavaCode01");
    System.out.println("Successfully compiled " + classObject.toString() + ".");

    Object instance = classObject.newInstance();
    Method method = classObject.getMethod("testMethod01", String.class);

    String value = (String) method.invoke(instance, "Test text and");
    assertEquals("The returned value is not correct (1).", "Test text and some other cool text.", value);

    value = (String) method.invoke(instance, "More text plus");
    assertEquals("The returned value is not correct (2).", "More text plus some other cool text.", value);
}

From source file:org.energyos.espi.common.repositories.jpa.ResourceRepositoryImpl.java

@SuppressWarnings("unchecked")
@Override//from  www  .  jav  a2 s.  c o  m
public <T extends IdentifiedObject> List<Long> findAllIdsByXPath(Class<T> clazz) {
    try {
        String findAllIdsByXPath = (String) clazz.getDeclaredField("QUERY_FIND_ALL_IDS_BY_XPATH_0")
                .get(String.class);
        Query query = em.createNamedQuery(findAllIdsByXPath);
        return query.getResultList();
    } catch (NoSuchFieldException | IllegalAccessException e) {
        System.out.printf("**** findAllIdsByXPath Exception: %s - %s\n", clazz.toString(), e.toString());
        throw new RuntimeException(e);
    }

}

From source file:org.energyos.espi.common.repositories.jpa.ResourceRepositoryImpl.java

@Override
public <T extends IdentifiedObject> Long findIdByXPath(Long id1, Class<T> clazz) {
    try {//from w  w  w  . j ava  2s.c o m
        String findIdByXPath = (String) clazz.getDeclaredField("QUERY_FIND_ID_BY_XPATH").get(String.class);
        Query query = em.createNamedQuery(findIdByXPath).setParameter("o1Id", id1);
        return (Long) query.getSingleResult();
    } catch (NoSuchFieldException | IllegalAccessException e) {
        System.out.printf("**** findIdByXPath(Long id1) Exception: %s - %s\n", clazz.toString(), e.toString());
        throw new RuntimeException(e);
    }
}