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:com.jaliansystems.activeMQLite.impl.ObjectRepository.java

private boolean paramMatches(Method method, Object[] params) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    if (params != null && parameterTypes.length != params.length
            || params == null && parameterTypes.length != 0)
        return false;
    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> class1 = parameterTypes[i];
        if (!class1.isPrimitive() && params[i] == null)
            continue;
        if (params[i] instanceof ObjectHandle) {
            params[i] = getObject(((ObjectHandle) params[i]));
        }//from   w  w w.  j  av a2  s. c o  m
        if (class1.isPrimitive()) {
            if (params[i] instanceof Boolean && class1 != Boolean.TYPE)
                return false;
            if (params[i] instanceof Integer && class1 != Integer.TYPE)
                return false;
            if (params[i] instanceof Long && class1 != Long.TYPE)
                return false;
            if (params[i] instanceof Short && class1 != Short.TYPE)
                return false;
            if (params[i] instanceof Float && class1 != Float.TYPE)
                return false;
            if (params[i] instanceof Double && class1 != Double.TYPE)
                return false;
            if (params[i] instanceof Byte && class1 != Byte.TYPE)
                return false;
        } else if (!class1.isInstance(params[i]))
            return false;
    }
    return true;
}

From source file:com.gzj.tulip.jade.rowmapper.DefaultRowMapperFactory.java

@Override
public RowMapper getRowMapper(StatementMetaData smd) {
    RowHandler rowHandler = smd.getAnnotation(RowHandler.class);

    // ?  RowMapper
    RowMapper rowMapper = null;/*w  w w .j  ava  2s.c om*/

    if (rowHandler != null) {
        if (rowHandler.rowMapper() != RowHandler.NotSettingRowMapper.class) {
            try {
                rowMapper = rowHandler.rowMapper().newInstance();
            } catch (Exception ex) {
                throw new BeanInstantiationException(rowHandler.rowMapper(), ex.getMessage(), ex);
            }
        } else if (rowHandler.rowMapperFactory() != RowHandler.NotSettingRowMapperFactory.class) {
            try {
                RowMapperFactory rowMapperFactory = rowHandler.rowMapperFactory().newInstance();
                rowMapper = rowMapperFactory.getRowMapper(smd);
            } catch (Exception ex) {
                throw new BeanInstantiationException(rowHandler.rowMapper(), ex.getMessage(), ex);
            }
        }
    }
    // 
    if (rowMapper == null) {
        //

        Class<?> returnClassType = smd.getMethod().getReturnType();
        Class<?> rowType = getRowType(smd);

        // BUGFIX: SingleColumnRowMapper ?  Primitive Type 
        if (rowType.isPrimitive()) {
            rowType = ClassUtils.primitiveToWrapper(rowType);
        }

        // ?(?2Map)
        if (TypeUtils.isColumnType(rowType)) {
            if (Map.class.isAssignableFrom(returnClassType)) {
                rowMapper = new MapEntryColumnRowMapper(smd, rowType);
            } else {
                rowMapper = new SingleColumnRowMapper(rowType);
            }
        }
        // Bean??????
        else {
            if (rowType == Map.class) {
                rowMapper = new ColumnMapRowMapper();
            } else if (rowType.isArray()) {
                rowMapper = new ArrayRowMapper(rowType);
            } else if ((rowType == List.class) || (rowType == Collection.class)) {
                rowMapper = new ListRowMapper(smd);
            } else if (rowType == Set.class) {
                rowMapper = new SetRowMapper(smd);
            } else {
                boolean checkColumns = (rowHandler == null) ? true : rowHandler.checkColumns();
                boolean checkProperties = (rowHandler == null) ? false : rowHandler.checkProperties();
                String key = rowType.getName() + "[checkColumns=" + checkColumns + "&checkProperties="
                        + checkProperties + "]";
                rowMapper = rowMappers.get(key);
                if (rowMapper == null) {
                    rowMapper = new BeanPropertyRowMapper(rowType, checkColumns, checkProperties); // jade's BeanPropertyRowMapper here
                    rowMappers.put(key, rowMapper);
                }
            }
            // DAOMaprowMapper?Map.Entry
            if (Map.class.isAssignableFrom(returnClassType)) {
                rowMapper = new MapEntryRowMapper(smd, rowMapper);
            }
        }
    }

    //

    if (rowMapper instanceof StatementAware) {
        ((StatementAware) rowMapper).setStatementMetaData(smd);
    }

    if (logger.isInfoEnabled()) {
        logger.info("using rowMapper " + rowMapper + " for " + smd);
    }

    return rowMapper;
}

From source file:com.edmunds.autotest.AutoTestGetterSetter.java

private Object createValue(Class<?> type, String errorMsg) {
    Object value = valueMap.get(type);

    if (value == null && !type.isPrimitive()) {
        value = ClassUtil.instanceClass(type, errorMsg);
    }/*  w  w w . jav  a  2 s .  co  m*/

    return value;
}

From source file:jef.tools.ArrayUtils.java

/**
 * ??//from ww  w . j a  v a 2  s  .  c o m
 * java.util.Arrays??????9???
 * 
 * @param a1
 *            Object
 * @param a2
 *            Object,
 * @return
 * @see java.util.Arrays#equals(boolean[], boolean[])
 * @see java.util.Arrays#equals(byte[], byte[])
 * @see java.util.Arrays#equals(char[], char[])
 * @see java.util.Arrays#equals(double[], double[])
 * @see java.util.Arrays#equals(float[], float[])
 * @see java.util.Arrays#equals(int[], int[])
 * @see java.util.Arrays#equals(long[], long[])
 * @see java.util.Arrays#equals(short[], short[])
 * @see java.util.Arrays#equals(Object[], Object[])
 * @throws IllegalArgumentException
 *             ?
 */
public static boolean equals(Object a1, Object a2) {
    if (a1 == a2)
        return true;
    if (a1 == null || a2 == null)
        return false;
    Class<?> clz1 = a1.getClass();
    Class<?> clz2 = a2.getClass();
    if (!clz1.isArray() || !clz2.isArray()) {
        throw new IllegalArgumentException("must comapre between two Array.");
    }
    clz1 = clz1.getComponentType();
    clz2 = clz2.getComponentType();
    if (clz1.isPrimitive() != clz2.isPrimitive()) {
        return false;
    }
    if (clz1 == int.class) {
        return Arrays.equals((int[]) a1, (int[]) a2);
    } else if (clz1 == short.class) {
        return Arrays.equals((short[]) a1, (short[]) a2);
    } else if (clz1 == long.class) {
        return Arrays.equals((long[]) a1, (long[]) a2);
    } else if (clz1 == float.class) {
        return Arrays.equals((float[]) a1, (float[]) a2);
    } else if (clz1 == double.class) {
        return Arrays.equals((double[]) a1, (double[]) a2);
    } else if (clz1 == boolean.class) {
        return Arrays.equals((boolean[]) a1, (boolean[]) a2);
    } else if (clz1 == byte.class) {
        return Arrays.equals((byte[]) a1, (byte[]) a2);
    } else if (clz1 == char.class) {
        return Arrays.equals((char[]) a1, (char[]) a2);
    } else {
        return Arrays.equals((Object[]) a1, (Object[]) a2);
    }
}

From source file:com.evolveum.midpoint.repo.sql.query2.restriction.PropertyRestriction.java

private Object checkValueType(Object value, ValueFilter filter) throws QueryException {

    Class expectedType = linkDefinition.getTargetDefinition().getJaxbClass();
    if (expectedType == null || value == null) {
        return value; // nothing to check here
    }//  w  ww  . jav  a  2s.  com

    if (expectedType.isPrimitive()) {
        expectedType = ClassUtils.primitiveToWrapper(expectedType);
    }

    //todo remove after some time [lazyman]
    //attempt to fix value type for polystring (if it was string in filter we create polystring from it)
    if (PolyString.class.equals(expectedType) && (value instanceof String)) {
        LOGGER.debug("Trying to query PolyString value but filter contains String '{}'.", filter);
        value = new PolyString((String) value, (String) value);
    }
    //attempt to fix value type for polystring (if it was polystringtype in filter we create polystring from it)
    if (PolyString.class.equals(expectedType) && (value instanceof PolyStringType)) {
        LOGGER.debug("Trying to query PolyString value but filter contains PolyStringType '{}'.", filter);
        PolyStringType type = (PolyStringType) value;
        value = new PolyString(type.getOrig(), type.getNorm());
    }

    if (String.class.equals(expectedType) && (value instanceof QName)) {
        //eg. shadow/objectClass
        value = RUtil.qnameToString((QName) value);
    }

    if (!expectedType.isAssignableFrom(value.getClass())) {
        throw new QueryException("Value should be type of '" + expectedType + "' but it's '" + value.getClass()
                + "', filter '" + filter + "'.");
    }
    return value;
}

From source file:mil.army.usace.data.dataquery.rdbms.implementations.OracleConverter.java

@Override
public Object convertType(Object obj, Method method)
        throws ClassNotFoundException, ConversionException, SQLException {
    Class methodParam = method.getParameterTypes()[0];
    if (obj == null)
        return null;
    else if (obj instanceof oracle.sql.TIMESTAMPTZ) {
        java.sql.Date sqlDate = ((oracle.sql.TIMESTAMPTZ) obj).dateValue(oc);
        return ConversionUtility.convertType(sqlDate, methodParam);
    } else {//from  w  w w  .j a v a2  s. c  o m
        if (methodParam.isPrimitive()) {
            return obj;
        } else {
            return ConversionUtility.convertType(obj, methodParam);
        }
    }
}

From source file:com._4dconcept.springframework.data.marklogic.core.convert.MappingMarklogicConverter.java

@Override
public <R> R read(Class<R> returnType, MarklogicContentHolder holder) {
    ResultItem resultItem = (ResultItem) holder.getContent();
    if (String.class.equals(returnType)) {
        return returnType.cast(resultItem.asString());
    }//from   w  ww . ja  v a  2s.  c o m

    R result = null;
    if (returnType.isPrimitive()) {
        try {
            Method method = MarklogicTypeUtils.primitiveMap.get(returnType).getMethod("valueOf", String.class);
            @SuppressWarnings("unchecked")
            R obj = (R) method.invoke(null, resultItem.asString());
            result = obj;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            LOGGER.debug("Unable to generate primitive value for type " + returnType.getName());
        }
    }

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

    ConversionService conversionService = getConversionService();

    if (conversionService.canConvert(resultItem.getClass(), returnType)) {
        R convert = conversionService.convert(resultItem, returnType);

        if (convert == null) {
            throw new ConversionFailedException(TypeDescriptor.forObject(resultItem),
                    TypeDescriptor.valueOf(returnType), resultItem, new NullPointerException());
        }

        return convert;
    } else {
        throw new ConverterNotFoundException(TypeDescriptor.forObject(resultItem),
                TypeDescriptor.valueOf(returnType));
    }
}

From source file:com.ms.commons.summer.web.util.json.JsonBeanUtils.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *///  w ww . j a  v a  2 s .  com
public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject() || root == null) {
        return root;
    }

    Class rootClass = root.getClass();
    if (rootClass.isInterface()) {
        throw new JSONException("Root bean is an interface. " + rootClass);
    }

    Map classMap = jsonConfig.getClassMap();
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names().iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) {
            continue;
        }
        String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        try {
            PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key);
            if (pd != null && pd.getWriteMethod() == null) {
                log.warn("Property '" + key + "' has no write method. SKIPPED.");
                continue;
            }

            if (!JSONUtils.isNull(value)) {
                if (value instanceof JSONArray) {
                    if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig);
                        setProperty(root, key, list, jsonConfig);
                    } else {
                        Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType());
                        Class targetInnerType = findTargetClass(key, classMap);
                        if (innerType.equals(Object.class) && targetInnerType != null
                                && !targetInnerType.equals(Object.class)) {
                            innerType = targetInnerType;
                        }
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null);
                        Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig);
                        if (innerType.isPrimitive() || JSONUtils.isNumber(innerType)
                                || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) {
                            array = JSONUtils.getMorpherRegistry()
                                    .morph(Array.newInstance(innerType, 0).getClass(), array);
                        } else if (!array.getClass().equals(pd.getPropertyType())) {
                            if (!pd.getPropertyType().equals(Object.class)) {
                                Morpher morpher = JSONUtils.getMorpherRegistry()
                                        .getMorpherFor(Array.newInstance(innerType, 0).getClass());
                                if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                    ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher(
                                            new BeanMorpher(innerType, JSONUtils.getMorpherRegistry()));
                                    JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher);
                                }
                                array = JSONUtils.getMorpherRegistry()
                                        .morph(Array.newInstance(innerType, 0).getClass(), array);
                            }
                        }
                        setProperty(root, key, array, jsonConfig);
                    }
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (pd != null) {
                        if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                            setProperty(root, key, null, jsonConfig);
                        } else if (!pd.getPropertyType().isInstance(value)) {
                            Morpher morpher = JSONUtils.getMorpherRegistry()
                                    .getMorpherFor(pd.getPropertyType());
                            if (IdentityObjectMorpher.getInstance().equals(morpher)) {
                                log.warn("Can't transform property '" + key + "' from " + type.getName()
                                        + " into " + pd.getPropertyType().getName()
                                        + ". Will register a default BeanMorpher");
                                JSONUtils.getMorpherRegistry().registerMorpher(
                                        new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry()));
                            }
                            setProperty(root, key,
                                    JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value),
                                    jsonConfig);
                        } else {
                            setProperty(root, key, value, jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        setProperty(root, key, value, jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + root.getClass().getName());
                    }
                } else {
                    if (pd != null) {
                        Class targetClass = pd.getPropertyType();
                        if (jsonConfig.isHandleJettisonSingleElementArray()) {
                            JSONArray array = new JSONArray().element(value, jsonConfig);
                            Class newTargetClass = findTargetClass(key, classMap);
                            newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                    : newTargetClass;
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass,
                                    null);
                            if (targetClass.isArray()) {
                                setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (Collection.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig),
                                        jsonConfig);
                            } else if (JSONArray.class.isAssignableFrom(targetClass)) {
                                setProperty(root, key, array, jsonConfig);
                            } else {
                                setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig),
                                        jsonConfig);
                            }
                        } else {
                            if (targetClass == Object.class) {
                                targetClass = findTargetClass(key, classMap);
                                targetClass = targetClass == null ? findTargetClass(name, classMap)
                                        : targetClass;
                            }
                            Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass,
                                    null);
                            setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                        }
                    } else if (root instanceof Map) {
                        Class targetClass = findTargetClass(key, classMap);
                        targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                        Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null);
                        setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig);
                    } else {
                        log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class "
                                + rootClass.getName());
                    }
                }
            } else {
                if (type.isPrimitive()) {
                    // assume assigned default value
                    log.warn("Tried to assign null value to " + key + ":" + type.getName());
                    setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig);
                } else {
                    setProperty(root, key, null, jsonConfig);
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return root;
}

From source file:com.industrieit.ohr.OHRJavassister.java

public static Class ohr(Class cll) {
    try {// w w w . j ava  2 s .c  o m
        //System.out.println("++++++++++ "+cll.getName());
        /*if (cll.getName().startsWith("ohr."))
        {
        throw new RuntimeException(cll.getName());
        }*/
        if (processed2.containsKey(cll)) {
            return processed2.get(cll);
        }

        HashSet<Long> handleOffsets = new HashSet<Long>();

        String cnam = cll.getName();
        if (!cnam.startsWith("ohr.")) {
            cnam = "ohr." + cll.getName();
            //cnam=cnam.substring(4);
        }

        Class cl = Class.forName(cnam.substring(4));

        int clnumber = incrementClsCounter();

        List<Integer> owned = new ArrayList<Integer>();

        //remove the old implementation if its around from another process
        String fname = "target/classes/" + cnam.replace(".", "/") + ".class";
        System.out.println("deleted" + fname + " " + (new File(fname).delete()));

        if (!Modifier.isAbstract(cl.getModifiers())) {
            throw new RuntimeException("not an abstract class " + cl.getName());
        }

        System.out.println("processing ohr " + cnam);

        CtClass bc = getDefault().getCtClass(cl.getName());
        CtClass cc = getDefault().makeClass(cnam, bc);

        StringBuilder initBuilder = new StringBuilder();
        initBuilder.append("public void internalInit() {\n");

        StringBuilder constructBuilder = new StringBuilder();
        constructBuilder.append("{");

        String intname = OHRBase.class.getName();
        System.out.println("intername is " + intname);

        CtClass ci = getDefault().getCtClass(intname);
        CtClass extern = getDefault().getCtClass(Externalizable.class.getName());

        //cc.addInterface(ci);
        cc.setInterfaces(new CtClass[] { ci, extern });
        cc.setSuperclass(bc);

        //add base implmenetation methods and properties
        setBaseMixinsPre(cc, false);

        //first long for id and other stuff
        long offset = 8;

        BeanInfo bi = Introspector.getBeanInfo(cl);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();

        for (int co = 0; co < propertyOrdering.length; co++) {
            Class cprop = propertyOrdering[co];

            for (int i = 0; i < pds.length; i++) {
                // Get property name
                String propName = pds[i].getName();

                if (propName.equals("class")) {
                    continue;
                }

                String typ = pds[i].getPropertyType().getName();
                Class type = pds[i].getPropertyType();
                //if (propName.startsWith("fath"))
                //PL.pl("[[[[["+type+" "+propName+" "+cprop);
                if (cprop == Object.class) {
                    //handle refs only
                    if (type.isPrimitive()) {
                        continue;
                    }
                    if (type == String.class) {
                        continue;
                    }
                    if (type == CharSequence.class) {
                        continue;
                    }
                    if (type == OHRLongArray.class) {
                        continue;
                    }
                    if (type == OHRIntArray.class) {
                        continue;
                    }
                    if (type == OHRShortArray.class) {
                        continue;
                    }
                    if (type == OHRByteArray.class) {
                        continue;
                    }
                    if (type == OHRBooleanArray.class) {
                        continue;
                    }
                    if (type == OHRDoubleArray.class) {
                        continue;
                    }
                    if (type == OHRFloatArray.class) {
                        continue;
                    }
                } else if (cprop != type) {
                    //PL.pl("skipping "+type+" "+cprop);
                    continue;
                }
                //PL.pl("[[[[[    " + type + " - " + propName + " - " + cprop);
                //System.out.println("--prop--" + propName);

                String rname = pds[i].getReadMethod().getName();
                String wname = null;
                if (pds[i].getWriteMethod() != null) {
                    wname = pds[i].getWriteMethod().getName();
                }

                boolean reifread = isMethodReifAnnotated(pds[i].getReadMethod());
                boolean reifwrite = isMethodReifAnnotated(pds[i].getWriteMethod());

                String wcons = getConsistencyAsString(pds[i].getWriteMethod());
                String rcons = getConsistencyAsString(pds[i].getReadMethod());

                System.out.println("TYPE " + pds[i].getPropertyType().getName() + " "
                        + pds[i].getPropertyType().getInterfaces());

                if (pds[i].getPropertyType() == String.class && isInlineString(pds[i])) {
                    //NOTE - only for inline strings - normal strings are handled as extrefs like any other object
                    System.out.println("ITS An inline string!!!!");

                    int length = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).length();
                    boolean trim = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class)
                            .trimOverflow();
                    boolean ascii = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).asciiOnly();

                    String wmeth = "public void " + wname + "(" + typ + " o) { ohwritestr" + wcons + "("
                            + offset + "l,o," + length + "," + trim + "," + ascii + "); }";
                    //add setter
                    CtMethod wmethod = CtNewMethod.make(wmeth, cc);

                    cc.addMethod(wmethod);

                    System.out.println(wmeth);
                    String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadstr" + rcons
                            + "(" + offset + "l," + ascii + "); }";
                    //add setter
                    CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                    //rmethod.getMethodInfo().addAttribute(attr);
                    cc.addMethod(rmethod);
                    System.out.println(rmeth);

                    int bytesperchar = ascii ? 1 : 2;

                    //pad to 16 bits
                    int ll = 4 + length * bytesperchar;
                    if (ll % 2 != 0) {
                        ll++;
                    }
                    offset += ll; //lebgth marker as well as unicode 16 encoded characters
                } else if (pds[i].getPropertyType() == CharSequence.class && isInlineString(pds[i])) {
                    //NOTE - only for inline strings - normal strings are handled as extrefs like any other object
                    System.out.println("ITS An inline charsequence!!!!");

                    int length = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).length();
                    boolean trim = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class)
                            .trimOverflow();
                    boolean ascii = pds[i].getWriteMethod().getAnnotation(InlineStringReify.class).asciiOnly();
                    String wmeth = "public void " + wname + "(" + typ + " o) { ohwritestr" + wcons + "("
                            + offset + "l,o," + length + "," + trim + "," + ascii + "); }";
                    //add setter
                    CtMethod wmethod = CtNewMethod.make(wmeth, cc);

                    cc.addMethod(wmethod);

                    System.out.println(wmeth);
                    String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadcs" + rcons
                            + "(" + offset + "l," + ascii + "); }";
                    //add setter
                    CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                    //rmethod.getMethodInfo().addAttribute(attr);
                    cc.addMethod(rmethod);
                    System.out.println(rmeth);

                    int bytesperchar = ascii ? 1 : 2;
                    //pad to 8 byte boundary!
                    int ll = (int) Math.ceil((4.0 + length * bytesperchar) / 8) * 8;
                    offset += ll; //lebgth marker as well as unicode 16 encoded characters
                } else if ((pds[i].getPropertyType() == OHRLongArray.class
                        || pds[i].getPropertyType() == OHRIntArray.class
                        || pds[i].getPropertyType() == OHRShortArray.class
                        || pds[i].getPropertyType() == OHRByteArray.class
                        || pds[i].getPropertyType() == OHRFloatArray.class
                        || pds[i].getPropertyType() == OHRDoubleArray.class
                        || pds[i].getPropertyType() == OHRBooleanArray.class)
                        && pds[i].getReadMethod().isAnnotationPresent(InlineArrayReify.class)) {

                    int bitsperitem = 0;
                    String cldef = null;
                    Class at = pds[i].getPropertyType();
                    boolean unchecked = pds[i].getReadMethod().isAnnotationPresent(UncheckedBoundsXXX.class);
                    if (at == OHRLongArray.class) {
                        bitsperitem = 8 * 8;
                        cldef = LongInlineOHRArray.class.getName();
                    } else if (at == OHRIntArray.class) {
                        bitsperitem = 4 * 8;
                        //cldef=IntInlineOHRArrayCop.class.getName();
                        if (unchecked) {
                            cldef = IntInlineOHRArrayUnchecked.class.getName();
                        } else {
                            cldef = IntInlineOHRArray.class.getName();
                        }
                    }
                    if (at == OHRDoubleArray.class) {
                        bitsperitem = 8 * 8;
                        cldef = DoubleInlineOHRArray.class.getName();
                    }
                    if (at == OHRFloatArray.class) {
                        bitsperitem = 4 * 8;
                        cldef = FloatInlineOHRArray.class.getName();
                    }
                    if (at == OHRShortArray.class) {
                        bitsperitem = 2 * 8;
                        cldef = ShortInlineOHRArray.class.getName();
                    }
                    if (at == OHRByteArray.class) {
                        bitsperitem = 1 * 8;
                        cldef = ByteInlineOHRArray.class.getName();
                    }
                    if (at == OHRBooleanArray.class) {
                        bitsperitem = 1;
                        cldef = BooleanInlineOHRArray.class.getName();
                    }
                    //NOTE - only for inline strings - normal strings are handled as extrefs like any other object
                    System.out.println("ITS An inline array!!!!");

                    int length = pds[i].getReadMethod().getAnnotation(InlineArrayReify.class).length();

                    long bytealloc = OHRInlineArrayHandler.getGenericArrayAllocationSize(bitsperitem, length);

                    //PL.pl("byte allocation for logn array length "+length+" "+bytealloc);

                    CtClass ctc = getDefault().getCtClass(cldef);

                    String varname = "var" + i;
                    CtField cf = new CtField(ctc, varname, cc);
                    cf.setModifiers(Modifier.PRIVATE);
                    cc.addField(cf);

                    //add data to constructor
                    initBuilder.append(
                            "com.industrieit.ohr.OHRInlineArrayHandler.initialiseInlineGenericArray(this.basePtr+"
                                    + offset + "l," + length + "l," + bitsperitem + ");\n");
                    constructBuilder.append(varname + "=new " + cldef + "(this," + offset + "l);\n");

                    //+ "//this.basePtr"+offset+"l);");

                    //String wmeth = "public void " + wname + "(" + typ + " o) { throw new java.lang.RuntimeException(\"not supported\"); }";
                    //add setter
                    //CtMethod wmethod = CtNewMethod.make(wmeth, cc);

                    //cc.addMethod(wmethod);

                    //System.out.println(wmeth);
                    String rmeth = "public " + typ + " " + rname + "() { return " + varname + "; }";
                    //add setter
                    CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                    //rmethod.getMethodInfo().addAttribute(attr);
                    cc.addMethod(rmethod);
                    System.out.println("||||||||" + rmeth + "|||||||||");

                    offset += bytealloc;
                } else if (pds[i].getPropertyType().isPrimitive()) {
                    //PL.pl("ITS A PRIMITIVE!");
                    int vv = 0;
                    if (cprop == long.class) {
                        vv = 8;
                    }
                    if (cprop == double.class) {
                        vv = 8;
                    }
                    if (cprop == int.class) {
                        vv = 4;
                    }
                    if (cprop == float.class) {
                        vv = 4;
                    }
                    if (cprop == short.class) {
                        vv = 2;
                    }
                    if (cprop == byte.class) {
                        vv = 1;
                    }

                    System.out.println(
                            "for " + pds[i].getName() + " typ is " + pds[i].getPropertyType().getName());

                    String wmeth = "public void " + wname + "(" + typ + " o) { ohwrite" + wcons + "(" + offset
                            + "l,o); }";
                    //add setter

                    //ConstPool constpool = cc.getClassFile().getConstPool();

                    if (reifwrite) {
                        CtMethod wmethod = CtNewMethod.make(wmeth, cc);
                        cc.addMethod(wmethod);
                        System.out.println("&&&&&&&" + wmeth);
                    }

                    String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohread" + typ
                            + rcons + "(" + offset + "l); }";
                    //add setter

                    //rmethod.getMethodInfo().addAttribute(attr);
                    if (reifread) {
                        CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                        cc.addMethod(rmethod);
                        System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&" + rmeth + vv);
                    }

                    offset += vv;
                } else {
                    System.out.println("ITS AN ASSUMED REIFY!!!");

                    if (pds[i].getWriteMethod().isAnnotationPresent(Owned.class)) {
                        owned.add(i);
                    }
                    //CtClass tc = getDefault().getCtClass(pds[i].getPropertyType().getName());
                    CtClass tc = getDefault().getCtClass(OHRBase.class.getName());
                    //String fnam="ohrt"+i;
                    //CtField f = new CtField(tc, fnam, cc);
                    //f.setModifiers(Modifier.PROTECTED);
                    //cc.addField(f);
                    //store by reify
                    //handleOffsets.add(offset);
                    String wmeth = "public void " + wname + "(" + typ + " o) { ohwritere" + wcons + "(" + offset
                            + "l,o); }";
                    //add setter
                    CtMethod wmethod = CtNewMethod.make(wmeth, cc);

                    if (reifwrite) {
                        cc.addMethod(wmethod);
                    }

                    System.out.println(wmeth);
                    //String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadre(" + offset + "l," + typ + ".class); }";
                    String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadre" + rcons
                            + "(" + offset + "l);  };";
                    //add setter
                    CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                    //rmethod.getMethodInfo().addAttribute(attr);
                    if (reifread) {
                        cc.addMethod(rmethod);
                    }
                    System.out.println(rmeth);
                    handleOffsets.add(offset);
                    offset += 8;
                }

                /* if (!isReif(type)) {
                        
                PL.pl(""+pds[i].getName()+" is a non reified handle!!!!");
                //store by handle
                handleOffsets.add(offset);
                String wmeth = "public void " + wname + "(" + typ + " o) { ohwritehand(" + offset + "l,o); }";
                //add setter
                CtMethod wmethod = CtNewMethod.make(wmeth, cc);
                        
                if (reifwrite) {
                    cc.addMethod(wmethod);
                }
                        
                System.out.println(wmeth);
                String rmeth = "public " + typ + " " + rname + "() { return (" + typ + ") ohreadhand(" + offset + "l); }";
                //add setter
                        
                CtMethod rmethod = CtNewMethod.make(rmeth, cc);
                //rmethod.getMethodInfo().addAttribute(attr);
                if (reifread) {
                    cc.addMethod(rmethod);
                }
                System.out.println(rmeth);
                }*/
            }

            //PL.pl("offset is "+offset);

        }
        //offset+=8;
        //ok create the get handleoffsets method

        //print out total byts allocated
        //PL.pl("%%%%%%%%%% TOTAL BYTES = " + offset);

        StringBuilder sb = new StringBuilder();
        sb.append("public long[] handleOffsets() { ");
        sb.append("long a[] = new long[").append(handleOffsets.size()).append("];");
        int c = 0;
        for (long l : handleOffsets) {
            sb.append("a[").append(c).append("]=").append(l).append("l;");
            c++;
        }
        sb.append("return a; }");

        System.out.println(sb.toString());
        CtMethod om = CtNewMethod.make(sb.toString(), cc);
        cc.addMethod(om);

        String sizem = "public long gsize() { return " + (offset) + "l; }";
        //PL.pl(sizem);

        CtMethod sm = CtNewMethod.make(sizem, cc);
        cc.addMethod(sm);

        //add clsid
        CtMethod cmid = CtNewMethod.make("public int ohclassId() { return " + clnumber + "; }", cc);
        cc.addMethod(cmid);

        setBaseMixinsPost(cc, false, owned, pds, constructBuilder, initBuilder);

        cc.writeFile("target/classes");

        /*for (Method me : cc.toClass().getDeclaredMethods()) { //test print, ok
         //System.out.println(me.getName());
         }*/

        Class ppp = Class.forName(cnam);
        Field f = ppp.getDeclaredField("u");
        f.setAccessible(true);
        f.set(ppp.newInstance(), USafe.getUnsafe());
        //synchronized (mutex)
        //{
        processed2.put(cl, ppp);
        processed2.put(ppp, ppp);
        cls[clnumber] = ppp;
        return ppp;
        //}

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.firejack.platform.core.validation.GreaterThanProcessor.java

@Override
public List<ValidationMessage> validate(Method readMethod, String property, Object value, ValidationMode mode)
        throws RuleValidationException {
    GreaterThan greaterThanAnnotation = readMethod.getAnnotation(GreaterThan.class);
    List<ValidationMessage> messages = null;
    if (greaterThanAnnotation != null) {
        messages = new ArrayList<ValidationMessage>();
        Class<?> returnType = readMethod.getReturnType();
        String parameterName = StringUtils.isBlank(greaterThanAnnotation.parameterName()) ? property
                : greaterThanAnnotation.parameterName();
        if (value != null) {
            if (returnType.getSuperclass() == Number.class || returnType.isPrimitive()) {
                boolean checkEquality = greaterThanAnnotation.checkEquality();
                Number val = null;
                if (returnType == Float.class || returnType == float.class) {
                    Float f = (Float) value;
                    if (checkEquality && f < greaterThanAnnotation.floatVal()
                            || !checkEquality && f <= greaterThanAnnotation.floatVal()) {
                        val = greaterThanAnnotation.floatVal();
                    }//from w ww  .j a v  a  2s  .c  o  m
                } else if (returnType == Double.class || returnType == double.class) {
                    Double d = (Double) value;
                    if (checkEquality && d < greaterThanAnnotation.doubleVal()
                            || !checkEquality && d <= greaterThanAnnotation.doubleVal()) {
                        val = greaterThanAnnotation.doubleVal();
                    }
                } else {
                    Long longValue = ((Number) value).longValue();
                    Long rangeValue = ((Integer) greaterThanAnnotation.intVal()).longValue();
                    if (checkEquality && longValue < rangeValue || !checkEquality && longValue <= rangeValue) {
                        val = greaterThanAnnotation.intVal();
                    }
                }
                if (val != null) {
                    messages.add(new ValidationMessage(property,
                            checkEquality ? greaterThanAnnotation.equalityMsgKey()
                                    : greaterThanAnnotation.msgKey(),
                            parameterName, val));
                }
            }
        }
    }
    return messages;
}