Example usage for java.lang Class isPrimitive

List of usage examples for java.lang Class isPrimitive

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native boolean isPrimitive();

Source Link

Document

Determines if the specified Class object represents a primitive type.

Usage

From source file:de.matzefratze123.heavyspleef.commands.base.CommandManagerService.java

protected void executeCommand(CommandContext context) {
    Method method = context.getCommand().getCommandMethod();
    Object instance = context.getCommand().getCommandClassInstance();

    boolean accessible = method.isAccessible();
    method.setAccessible(true);//  www. j  a v a2 s.co m

    //Analyse the method
    //Default method format is: methodName(CommandContext)

    try {
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length == 0) {
            //No parameters in this method, so just invoke it
            method.invoke(instance);
        } else {
            Object[] parameterValues = new Object[parameterTypes.length];

            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> parameterType = parameterTypes[i];

                if (parameterType == CommandContext.class) {
                    parameterValues[i] = context;
                } else if (plugin.getClass() == parameterType) {
                    parameterValues[i] = plugin;
                } else if (parameterType.isPrimitive()) {
                    parameterValues[i] = getDefaultPrimitiveValue(parameterType);
                } else {
                    for (Object arg : args) {
                        if (parameterType.isInstance(arg)) {
                            parameterValues[i] = arg;
                            break;
                        }
                    }
                }
            }

            method.invoke(instance, parameterValues);
        }
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();

        if (cause instanceof CommandException) {
            ((CommandException) cause).sendToPlayer(context.getSender());
        } else {
            logger.log(Level.SEVERE,
                    "Unhandled exception executing command \"" + context.getCommand().getName() + "\"", cause);
        }
    } catch (IllegalAccessException | IllegalArgumentException e) {
        logger.log(Level.SEVERE,
                "Could not invoke command method for '" + context.getCommand().getFullyQualifiedName() + "'",
                e);
    } catch (Exception e) {
        logger.log(Level.SEVERE,
                "Unhandled exception executing command '" + context.getCommand().getFullyQualifiedName() + "'",
                e);
    } finally {
        method.setAccessible(accessible);
    }
}

From source file:com.dotweblabs.twirl.gae.GaeMarshaller.java

public static <T> T createObjectFrom(Class<T> clazz, Entity source) {
    T obj = null;//w w w  . java 2  s . com
    Map<String, Object> props = source.getProperties();
    Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator();
    if (props.size() > 1) {
        if (clazz == List.class) {
            throw new RuntimeException("Not yet implemented");
        } else if (clazz == Map.class) {
            throw new RuntimeException("Not yet implemented");
        } else {
            //obj = createPOJOFrom(clazz, createMapFromEntity(source));
        }
    } else if (props.size() == 1) {
        Map.Entry<String, Object> entry = it.next();
        Object value = entry.getValue();
        if (clazz.isPrimitive()) {
            obj = (T) value;
        } else if (clazz == String.class) {
            String prop = String.valueOf(value);
            obj = (T) prop;
        } else if (clazz == Number.class || clazz == Long.class || clazz == Integer.class) {
            Long prop = Long.valueOf(String.valueOf(value));
            obj = (T) prop;
        } else if (clazz == Boolean.class) {
            Boolean prop = Boolean.valueOf(String.valueOf(value));
            obj = (T) prop;
        }
    } else {
        // empty
    }
    return obj;
}

From source file:hu.bme.mit.sette.common.validator.reflection.ClassValidator.java

/**
 * Sets the required type for the Java class.
 *
 * @param type/* w ww  . j a  va  2 s  .  com*/
 *            the required type for the Java class.
 * @return this object
 */
public ClassValidator type(final ClassType type) {
    Validate.notNull(type, "The type must not be null");

    if (getSubject() != null) {
        Class<?> javaClass = getSubject();
        boolean isTypeValid = false;

        switch (type) {
        case CLASS:
            isTypeValid = !javaClass.isInterface() && !javaClass.isEnum() && !javaClass.isAnnotation()
                    && !javaClass.isPrimitive() && !javaClass.isArray();
            break;

        case REGULAR_CLASS:
            isTypeValid = !javaClass.isInterface() && !javaClass.isEnum() && !javaClass.isAnnotation()
                    && !javaClass.isPrimitive() && !javaClass.isArray() && !javaClass.isMemberClass()
                    && !javaClass.isAnonymousClass() && !javaClass.isLocalClass();
            break;

        case MEMBER_CLASS:
            isTypeValid = !javaClass.isInterface() && !javaClass.isEnum() && !javaClass.isAnnotation()
                    && !javaClass.isPrimitive() && !javaClass.isArray() && javaClass.isMemberClass();
            break;

        case ANONYMOUS_CLASS:
            isTypeValid = !javaClass.isInterface() && !javaClass.isEnum() && !javaClass.isAnnotation()
                    && !javaClass.isPrimitive() && !javaClass.isArray() && javaClass.isAnonymousClass();
            break;

        case LOCAL_CLASS:
            isTypeValid = !javaClass.isInterface() && !javaClass.isEnum() && !javaClass.isAnnotation()
                    && !javaClass.isPrimitive() && !javaClass.isArray() && javaClass.isLocalClass();
            break;

        case INTERFACE:
            isTypeValid = javaClass.isInterface();
            break;

        case REGULAR_INTERFACE:
            isTypeValid = javaClass.isInterface() && !javaClass.isMemberClass();
            break;

        case MEMBER_INTERFACE:
            isTypeValid = javaClass.isInterface() && javaClass.isMemberClass();
            break;

        case ENUM:
            isTypeValid = javaClass.isEnum();
            break;

        case REGULAR_ENUM:
            isTypeValid = javaClass.isEnum() && !javaClass.isMemberClass();
            break;

        case MEMBER_ENUM:
            isTypeValid = javaClass.isEnum() && javaClass.isMemberClass();
            break;

        case ANNOTATION:
            isTypeValid = javaClass.isAnnotation();
            break;

        case REGULAR_ANNOTATION:
            isTypeValid = javaClass.isAnnotation() && !javaClass.isMemberClass();
            break;

        case MEMBER_ANNOTATION:
            isTypeValid = javaClass.isAnnotation() && javaClass.isMemberClass();
            break;

        case PRIMITIVE:
            isTypeValid = javaClass.isPrimitive();
            break;

        case ARRAY:
            isTypeValid = javaClass.isArray();
            break;

        default:
            throw new UnsupportedOperationException("Unknown class type: " + type);
        }

        if (!isTypeValid) {
            this.addException(
                    String.format("The Java class must have the specified type\n" + "(type: [%s])", type));
        }
    }

    return this;
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.BeanInspectorPanel.java

public void exploreBean(DefaultMutableTreeNode root, String classname, String parentPath) {
    try {/*ww  w.  j  a va  2 s. c o m*/

        root.removeAllChildren();
        if (parentPath.length() > 0)
            parentPath += ".";

        Class clazz = Class.forName(classname, true, IReportManager.getInstance().getReportClassLoader());

        java.beans.PropertyDescriptor[] pd = org.apache.commons.beanutils.PropertyUtils
                .getPropertyDescriptors(clazz);
        for (int nd = 0; nd < pd.length; ++nd) {
            String fieldName = pd[nd].getName();
            if (pd[nd].getPropertyType() != null && pd[nd].getReadMethod() != null) {
                Class clazzRT = pd[nd].getPropertyType();

                if (clazzRT.isPrimitive()) {
                    clazzRT = MethodUtils.getPrimitiveWrapper(clazzRT);
                }

                String returnType = clazzRT.getName();

                JRDesignField field = new JRDesignField();
                field.setName(fieldName);
                field.setValueClassName(returnType);

                if (isPathOnDescription()) {
                    field.setDescription(parentPath + fieldName);
                } else {
                    field.setName(parentPath + fieldName);
                }

                TreeJRField jtf = new TreeJRField();

                jtf.setField(field);
                jtf.setObj(pd[nd].getPropertyType());

                boolean bChildrens = true;
                if (pd[nd].getPropertyType().isPrimitive()
                        || pd[nd].getPropertyType().getName().startsWith("java.lang.")) {
                    bChildrens = false;
                }
                root.add(new DefaultMutableTreeNode(jtf, bChildrens));
            }
        }

        jTree1.expandPath(new TreePath(root.getPath()));
        jTree1.updateUI();

    } catch (ClassNotFoundException cnf) {
        javax.swing.JOptionPane.showMessageDialog(this, Misc.formatString( //"messages.BeanInspectorPanel.classNotFoundError",
                I18n.getString("BeanInspectorPanel.Message.Error"), new Object[] { cnf.getMessage() }),
                I18n.getString("BeanInspectorPanel.Message.Error2"), javax.swing.JOptionPane.ERROR_MESSAGE);
        return;
    } catch (Exception ex) {
        ex.printStackTrace();
        javax.swing.JOptionPane.showMessageDialog(this, ex.getMessage(),
                I18n.getString("BeanInspectorPanel.Message.Error2"), javax.swing.JOptionPane.ERROR_MESSAGE);
        return;
    }
}

From source file:cc.aileron.accessor.TypeConvertorImpl.java

@Override
public Object convert(final Object value, final Class<?> from, final Class<?> to) {
    /*/*ww  w. j av a  2  s. c o  m*/
     * to boolean
     */
    if (Boolean.class.isAssignableFrom(to) || to == Boolean.TYPE) {
        if (value == null) {
            return false;
        }
        if (Boolean.class.isAssignableFrom(from) || Boolean.TYPE == from) {
            return value;
        }
        if (Number.class.isAssignableFrom(from) || from.isPrimitive()) {
            return ((Number) value).intValue() != 0;
        }
        if (BooleanGetAccessor.class.isAssignableFrom(from)) {
            final BooleanGetAccessor accessor = (BooleanGetAccessor) value;
            return accessor.toBoolean();
        }
        if (String.class == from) {
            return Boolean.parseBoolean(String.class.cast(value));
        }
        return true;
    }

    /*
     * to primitive is null
     */
    if (to.isPrimitive() && value == null) {
        return 0;
    }

    /*
     * value is null
     */
    if (value == null) {
        return null;
    }

    /*
     * to primitive from string
     */
    if (to.isPrimitive() && String.class == from) {
        if (StringUtils.isEmpty((String) value)) {
            return 0;
        }
        final Integer number = Integer.valueOf((String) value);
        return numberToPrimitive(number, to);
    }

    /*
     * to primitive from number
     */
    if (to.isPrimitive() && Number.class.isAssignableFrom(from)) {
        final Number number = (Number) value;
        return numberToPrimitive(number, to);
    }

    /*
     * to number from string
     */
    if (Number.class.isAssignableFrom(to) && String.class == from) {
        final String string = (String) value;
        if (Boolean.TYPE == to) {
            return Boolean.parseBoolean(string);
        }
        if (Character.TYPE == to) {
            throw new UnsupportedOperationException();
        }
        final Number number = Integer.valueOf(string);
        return numberToPrimitive(number, to);
    }

    /*
     * to number from number-get-accessor
     */
    if (Number.class.isAssignableFrom(to) && value instanceof NumberGetAccessor) {
        final NumberGetAccessor accessor = (NumberGetAccessor) value;
        return accessor.toNumber();
    }

    /*
     * to string from not string
     */
    if (to == String.class && !(value instanceof String)) {
        return value.toString();
    }

    return value;
}

From source file:com.sqewd.open.dal.core.persistence.handlers.StringArrayConvertor.java

private Object getArrayData(String[] data, Field field) throws Exception {
    Class<?> type = field.getType().getComponentType();
    if (type.equals(String.class)) {
        return data;
    } else if (EnumPrimitives.isPrimitiveType(type)) {
        EnumPrimitives et = EnumPrimitives.type(type);
        if (type.isPrimitive()) {
            switch (et) {
            case ECharacter:
                char[] carr = new char[data.length];
                for (int ii = 0; ii < carr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        carr[ii] = data[ii].charAt(0);
                }//  w ww  .  j  av  a  2s  .  c o m
                return carr;
            case EShort:
                short[] sarr = new short[data.length];
                for (int ii = 0; ii < sarr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        sarr[ii] = Short.parseShort(data[ii]);
                }
                return sarr;
            case EInteger:
                int[] iarr = new int[data.length];
                for (int ii = 0; ii < iarr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        iarr[ii] = Integer.parseInt(data[ii]);
                }
                return iarr;
            case ELong:
                long[] larr = new long[data.length];
                for (int ii = 0; ii < larr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        larr[ii] = Long.parseLong(data[ii]);
                }
                return larr;
            case EFloat:
                float[] farr = new float[data.length];
                for (int ii = 0; ii < farr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        farr[ii] = Float.parseFloat(data[ii]);
                }
                return farr;
            case EDouble:
                double[] darr = new double[data.length];
                for (int ii = 0; ii < darr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        darr[ii] = Double.parseDouble(data[ii]);
                }
                return darr;
            }
        } else {
            switch (et) {
            case ECharacter:
                Character[] carr = new Character[data.length];
                for (int ii = 0; ii < carr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        carr[ii] = data[ii].charAt(0);
                }
                return carr;
            case EShort:
                Short[] sarr = new Short[data.length];
                for (int ii = 0; ii < sarr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        sarr[ii] = Short.parseShort(data[ii]);
                }
                return sarr;
            case EInteger:
                Integer[] iarr = new Integer[data.length];
                for (int ii = 0; ii < iarr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        iarr[ii] = Integer.parseInt(data[ii]);
                }
                return iarr;
            case ELong:
                Long[] larr = new Long[data.length];
                for (int ii = 0; ii < larr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        larr[ii] = Long.parseLong(data[ii]);
                }
                return larr;
            case EFloat:
                Float[] farr = new Float[data.length];
                for (int ii = 0; ii < farr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        farr[ii] = Float.parseFloat(data[ii]);
                }
                return farr;
            case EDouble:
                Double[] darr = new Double[data.length];
                for (int ii = 0; ii < darr.length; ii++) {
                    if (data[ii] != null && !data[ii].isEmpty())
                        darr[ii] = Double.parseDouble(data[ii]);
                }
                return darr;
            }
        }
    } else if (type.equals(Date.class)) {
        Date[] dtarr = new Date[data.length];
        for (int ii = 0; ii < dtarr.length; ii++) {
            if (data[ii] != null && !data[ii].isEmpty()) {
                dtarr[ii] = DateUtils.fromString(data[ii]);
            }
        }
    }
    throw new Exception("Unsupported Array element type [" + type.getCanonicalName() + "]");
}

From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java

/**
 * TODO: provide support for nested JSON objects
 * TODO: provide support for embedded JSON Arrays
 *
 * @param jsonObject//  ww w. j a va  2s.c  o m
 * @param beanToBeCreatedClass
 * @param <T>
 * @return
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws JSONException
 * @throws NoSuchMethodException
 * @throws java.lang.reflect.InvocationTargetException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T unmarshall(JSONObject jsonObject, Class<T> beanToBeCreatedClass)
        throws IllegalAccessException, InstantiationException, JSONException, NoSuchMethodException,
        InvocationTargetException {
    T value = beanToBeCreatedClass.getConstructor().newInstance();

    Iterator keys = jsonObject.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        Object field = jsonObject.get(key);

        //  capitalise to standard setter pattern
        String methodName = SETTER_PREFIX + key.substring(0, 1).toUpperCase() + key.substring(1);

        //System.err.println("method name:" + methodName);

        Method method = getCandidateMethod(beanToBeCreatedClass, methodName);

        if (method != null) {
            Class clazz = method.getParameterTypes()[0];

            // discriminate based on type
            if (field.equals(JSONObject.NULL)) {
                method.invoke(value, clazz.cast(null));
            } else if (field instanceof String) {
                // check if we're an enum
                if (clazz.isEnum()) {
                    Object enm = clazz.getMethod("valueOf", String.class).invoke(null, field);
                    try {
                        beanToBeCreatedClass.getMethod(methodName, clazz).invoke(value, enm);
                        continue;
                    } catch (NoSuchMethodException e) {
                        // that means there was no such method, proceed
                    }
                }

                // string shall be used directly, either to set or as constructor parameter (if suitable)
                try {
                    beanToBeCreatedClass.getMethod(methodName, String.class).invoke(value, field);
                    continue;
                } catch (NoSuchMethodException e) {
                    // that means there was no such method, proceed
                }
                // or maybe there is method with suitable parameter?
                if (clazz.isPrimitive() && primitves.get(clazz) != null) {
                    clazz = primitves.get(clazz);
                }
                try {
                    method.invoke(value, clazz.getConstructor(String.class).newInstance(field));
                } catch (NoSuchMethodException nsme) {
                    // we are failed here,  but so what? be lenient
                }

            }
            // we are done with string
            else if (clazz.isArray() || clazz.isAssignableFrom(List.class)) {
                // JSON array corresponds either to array type, or to some collection
                if (field instanceof JSONObject) {
                    JSONArray array = new JSONArray();
                    array.put(field);
                    field = array;
                }

                // we are interested in arrays for now
                if (clazz.isArray()) {
                    // populate field value from JSON Array
                    Object fieldValue = populateRecursive(clazz, field);
                    method.invoke(value, fieldValue);
                } else if (clazz.isAssignableFrom(List.class)) {
                    try {
                        Type type = method.getGenericParameterTypes()[0];
                        if (type instanceof ParameterizedType) {
                            Type param = ((ParameterizedType) type).getActualTypeArguments()[0];
                            if (param instanceof Class) {
                                Class c = (Class) param;

                                // populate field value from JSON Array
                                Object fieldValue = populateRecursiveList(clazz, c, field);
                                method.invoke(value, fieldValue);
                            }
                        }
                    } catch (Exception e) {
                        // failed
                    }
                }

            } else if (field instanceof JSONObject) {
                // JSON object means nested bean - process recursively
                method.invoke(value, unmarshall((JSONObject) field, clazz));
            } else if (clazz.equals(Date.class)) {
                method.invoke(value, new Date((Long) field));
            } else {

                // fallback here,  types not yet processed will be
                // set directly ( if possible )
                // TODO: guard this? for better leniency
                method.invoke(value, field);
            }

        }
    }
    return value;
}

From source file:com.nginious.http.serialize.JsonSerializerCreator.java

/**
 * Creates a JSON serializer for the specified bean class unless a serializer has already been
 * created. Created serializers are cached and returned on subsequent calls to this method.
 * //w ww  .  j  a v a  2s. c  o  m
 * @param factory serializer factory
 * @param <T> class type for bean
 * @param beanClazz bean class for which a serializer should be created
 * @return the created serializer
 * @throws SerializerFactoryException if unable to create serializer or class is not a bean
 */
@SuppressWarnings("unchecked")
<T> JsonSerializer<T> create(SerializerFactoryImpl factory, Class<T> beanClazz)
        throws SerializerFactoryException {
    JsonSerializer<T> serializer = (JsonSerializer<T>) serializers.get(beanClazz);

    if (serializer != null) {
        return serializer;
    }

    try {
        synchronized (this) {
            serializer = (JsonSerializer<T>) serializers.get(beanClazz);

            if (serializer != null) {
                return serializer;
            }

            checkSerializability(beanClazz, "json");
            String intBeanClazzName = Serialization.createInternalClassName(beanClazz);
            Method[] methods = beanClazz.getMethods();

            String intSerializerClazzName = new StringBuffer(intBeanClazzName).append("JsonSerializer")
                    .toString();

            // Create class
            ClassWriter writer = new ClassWriter(0);
            String signature = Serialization.createClassSignature("com/nginious/http/serialize/JsonSerializer",
                    intBeanClazzName);
            writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intSerializerClazzName, signature,
                    "com/nginious/http/serialize/JsonSerializer", null);

            // Create constructor
            Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonSerializer");

            // Create serialize method
            MethodVisitor visitor = createSerializeMethod(writer, intBeanClazzName);

            for (Method method : methods) {
                Serializable info = method.getAnnotation(Serializable.class);
                boolean canSerialize = info == null
                        || (info != null && info.serialize() && info.types().indexOf("json") > -1);

                if (canSerialize && method.getName().startsWith("get") && !method.getName().equals("getClass")
                        && method.getReturnType() != null && method.getParameterTypes().length == 0) {
                    Class<?> returnType = method.getReturnType();
                    String propertyName = getPropertyName(method);

                    if (returnType.isPrimitive()) {
                        if (returnType.equals(boolean.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeBoolean",
                                    "Z", "Z", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(double.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDouble",
                                    "D", "D", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(float.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeFloat",
                                    "F", "F", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(int.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeInt",
                                    "I", "I", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(long.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeLong",
                                    "J", "J", intBeanClazzName, method.getName(), propertyName);
                        } else if (returnType.equals(short.class)) {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeShort",
                                    "S", "S", intBeanClazzName, method.getName(), propertyName);
                        }
                    } else if (Collection.class.isAssignableFrom(returnType)) {
                        Class<?> collectionType = canSerializeGenericCollectionType(method, "json");

                        if (collectionType != null) {
                            createBeanCollectionSerializationCode(visitor, intBeanClazzName, method.getName(),
                                    propertyName, returnType, collectionType);
                        } else {
                            createObjectCollectionSerializationCode(visitor, returnType, intBeanClazzName,
                                    method.getName(), propertyName);
                        }
                    } else if (returnType.equals(Calendar.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeCalendar",
                                "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName,
                                method.getName(), propertyName);
                    } else if (returnType.equals(Date.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeDate",
                                "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else if (returnType.equals(String.class)) {
                        createPropertySerializationCode(visitor, intSerializerClazzName, "serializeString",
                                "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName(),
                                propertyName);
                    } else {
                        info = returnType.getAnnotation(Serializable.class);
                        canSerialize = info != null && info.serialize() && info.types().indexOf("json") > -1;

                        if (canSerialize) {
                            createBeanSerializationCode(visitor, method.getName(), propertyName, returnType,
                                    intBeanClazzName);
                        } else {
                            createPropertySerializationCode(visitor, intSerializerClazzName, "serializeObject",
                                    "Ljava/lang/Object;", "L" + returnType.getName().replace('.', '/') + ";",
                                    intBeanClazzName, method.getName(), propertyName);
                        }
                    }
                }
            }

            visitor.visitInsn(Opcodes.RETURN);
            visitor.visitMaxs(8, 7);
            visitor.visitEnd();

            writer.visitEnd();
            byte[] clazzBytes = writer.toByteArray();
            ClassLoader controllerLoader = null;

            if (classLoader.hasLoaded(beanClazz)) {
                controllerLoader = beanClazz.getClassLoader();
            } else {
                controllerLoader = this.classLoader;
            }

            Class<?> clazz = Serialization.loadClass(controllerLoader, intSerializerClazzName.replace('/', '.'),
                    clazzBytes);
            serializer = (JsonSerializer<T>) clazz.newInstance();
            String propertyName = Serialization.createPropertyNameFromClass(beanClazz);
            serializer.setName(propertyName);
            serializer.setType(beanClazz);
            serializer.setSerializerFactory(factory);
            serializers.put(beanClazz, serializer);
            return serializer;
        }
    } catch (IllegalAccessException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    } catch (InstantiationException e) {
        throw new SerializerFactoryException("Can't create JSON serializer for " + beanClazz.getName(), e);
    }
}

From source file:org.walkmod.conf.entities.impl.ConfigurationImpl.java

private List<PropertyDefinition> getProperties(Object o) {
    List<PropertyDefinition> result = new LinkedList<PropertyDefinition>();
    PropertyDescriptor[] properties = BeanUtils.getPropertyDescriptors(o.getClass());
    if (properties != null) {
        for (PropertyDescriptor pd : properties) {
            if (pd.getWriteMethod() != null) {
                String name = pd.getDisplayName();
                Class<?> clazz = pd.getPropertyType();
                String type = clazz.getSimpleName();
                String value = "";
                if (String.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz)
                        || clazz.isPrimitive()) {
                    if (pd.getReadMethod() != null) {
                        try {
                            value = pd.getReadMethod().invoke(o).toString();
                        } catch (Exception e) {
                        }//  w  w w.ja v a2 s.c o m
                    } else {
                        Field[] fields = o.getClass().getDeclaredFields();
                        boolean found = false;
                        for (int i = 0; i < fields.length && !found; i++) {
                            if (fields[i].getName().equals(name)) {
                                found = true;
                                fields[i].setAccessible(true);
                                try {
                                    value = fields[i].get(o).toString();
                                } catch (Exception e) {
                                }
                            }
                        }
                    }
                }

                PropertyDefinition item = new PropertyDefinitionImpl(type, name, value);

                result.add(item);
            }
        }
    }
    return result;
}

From source file:net.sf.jrf.domain.PersistentObjectDynaProperty.java

/** Constructs instance and property name and class.
* @param name property name.//from   ww  w. j a  v  a  2 s . c  om
* @param cls value object <code>Class</code>.
* @param readMethodName name of the read <code>Method</code>
* @param writeMethodName name of the write <code>Method</code>
*/
public PersistentObjectDynaProperty(String name, Class cls, String readMethodName, String writeMethodName) {
    super(name, cls);
    this.readMethodName = readMethodName;
    this.writeMethodName = writeMethodName;
    if (cls.isPrimitive()) {
        if (cls.equals(Boolean.TYPE))
            primitiveWrapperClass = Boolean.class;
        else if (cls.equals(Byte.TYPE))
            primitiveWrapperClass = Byte.class;
        else if (cls.equals(Character.TYPE))
            primitiveWrapperClass = Character.class;
        else if (cls.equals(Double.TYPE))
            primitiveWrapperClass = Double.class;
        else if (cls.equals(Float.TYPE))
            primitiveWrapperClass = Float.class;
        else if (cls.equals(Integer.TYPE))
            primitiveWrapperClass = Integer.class;
        else if (cls.equals(Long.TYPE))
            primitiveWrapperClass = Long.class;
        else if (cls.equals(Short.TYPE))
            primitiveWrapperClass = Short.class;

    } else if (java.util.List.class.isAssignableFrom(cls) || cls.isArray()) {
        indexed = true;
    } else if (java.util.Map.class.isAssignableFrom(cls)) {
        mapped = true;
    }
}