Java Code Examples for java.io.Serializable.getClass()

The following are Jave code examples for showing how to use getClass() of the java.io.Serializable class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: alfresco-repository   File: AbstractRenderingEngine.java   View Source Code Vote up 6 votes
/**
 * Gets the value for the named parameter. Checks the type of the parameter
 * is correct and throws a {@link RenditionServiceException} if it isn't.
 * Returns <code>null</code> if the parameter value is <code>null</code>
 * 
 * @param paramName the name of the parameter being checked.
 * @param clazz the expected {@link Class} of the parameter value.
 * @param definition the {@link RenditionDefinition} containing the
 *            parameters.
 * @return the parameter value or <code>null</code>.
 */
@SuppressWarnings("unchecked")
public static <T> T getCheckedParam(String paramName, Class<T> clazz, RenditionDefinition definition)
{
    Serializable value = definition.getParameterValue(paramName);
    if (value == null)
        return null;
    else
    {
        if(clazz == null)
            throw new RenditionServiceException("The class must not be null!", new NullPointerException());
        Class<? extends Serializable> valueClass = value.getClass();
        if ( !clazz.isAssignableFrom(valueClass))
        {
            throw new RenditionServiceException("The parameter: " + paramName + " must be of type: "
                        + clazz.getName() + "but was of type: " + valueClass.getName());
        }
        else
            return (T) value;
    }
}
 
Example 2
Project: alfresco-repository   File: DefaultPropertyTypeConverter.java   View Source Code Vote up 5 votes
/**
 * Determines if the value can be adequately recreated (to equality) by creating
 * a new instance.  For example, a <b>java.util.HashMap</b> is constructable provided
 * that the map is empty.
 * <p>
 * Subclasses can override this to handle any well-known types, and in conjunction with
 * {@link #constructInstance(String)}, even choose to return <tt>true</tt> if it needs a
 * non-default constructor.
 * 
 * @param value             the value to check
 * @return                  Returns <tt>true</tt> if the value can be reconstructed by
 *                          instantiation using a default constructor
 */
protected boolean isConstructable(Serializable value)
{
    // Is it in the set directly
    Class<?> valueClazz = value.getClass();
    // Check for default constructor
    try
    {
        valueClazz.getConstructor();
    }
    catch (NoSuchMethodException e)
    {
        // Can't reconstruct using just a type name
        return false;
    }
    // Maps and Collections
    if (value instanceof Map<?, ?>)
    {
        Map<?, ?> mapValue = (Map<?, ?>) value;
        return mapValue.isEmpty();
    }
    else if (value instanceof Collection<?>)
    {
        Collection<?> collectionValue = (Collection<?>) value;
        return collectionValue.isEmpty();
    }
    else
    {
        // We don't recognise it
        return false;
    }
}
 
Example 3
Project: alfresco-repository   File: NodePropertyHelper.java   View Source Code Vote up 5 votes
/**
 * Helper method to convert the <code>Serializable</code> value into a full, persistable {@link NodePropertyValue}.
 * <p>
 * Where the property definition is null, the value will take on the {@link DataTypeDefinition#ANY generic ANY}
 * value.
 * <p>
 * Collections are NOT supported. These must be split up by the calling code before calling this method. Map
 * instances are supported as plain serializable instances.
 * 
 * @param propertyDef the property dictionary definition, may be null
 * @param value the value, which will be converted according to the definition - may be null
 * @return Returns the persistable property value
 */
public NodePropertyValue makeNodePropertyValue(PropertyDefinition propertyDef, Serializable value)
{
    // get property attributes
    final QName propertyTypeQName;
    if (propertyDef == null) // property not recognised
    {
        // allow it for now - persisting excess properties can be useful sometimes
        propertyTypeQName = DataTypeDefinition.ANY;
    }
    else
    {
        propertyTypeQName = propertyDef.getDataType().getName();
    }
    try
    {
        NodePropertyValue propertyValue = null;
        propertyValue = new NodePropertyValue(propertyTypeQName, value);

        // done
        return propertyValue;
    }
    catch (TypeConversionException e)
    {
        throw new TypeConversionException(
                "The property value is not compatible with the type defined for the property: \n" +
                "   property: " + (propertyDef == null ? "unknown" : propertyDef) + "\n" +
                "   value: " + value + "\n" +
                "   value type: " + value.getClass(),
                e);
    }
}
 
Example 4
Project: parabuild-ci   File: AbstractEntityPersister.java   View Source Code Vote up 5 votes
/**
 * Return a new instance initialized with the given identifier
 */
public Object instantiate(Serializable id) throws HibernateException {
	if ( hasEmbeddedIdentifier && id.getClass()==mappedClass ) {
		return id;
	}
	else {
		if (abstractClass) throw new HibernateException("Cannot instantiate abstract class or interface: " + className);
		final Object result;
		if (optimizer != null) { 
			try {
				result = fastClass.newInstance();
			}
			catch (Throwable t) {
				throw new InstantiationException("Could not instantiate entity with CGLIB: ", mappedClass, t);
			}
		}
		else {
			try {
				result = constructor.newInstance(null);
			}
			catch (Exception e) {
				throw new InstantiationException("Could not instantiate entity: ", mappedClass, e);
			}
		}
		setIdentifier(result, id);
		return result;
	}
}
 
Example 5
Project: jdk8u-jdk   File: Serial.java   View Source Code Vote up 5 votes
/**
 * Checks that the given object serializes to the expected class.
 */
static void checkSerialClassName(Serializable obj, String expected) {
    String cn = serialClassName(obj);
    if (!cn.equals(expected))
        throw new RuntimeException(obj.getClass() + " serialized as " + cn
            + ", expected " + expected);
}
 
Example 6
Project: openjdk-jdk10   File: Serial.java   View Source Code Vote up 5 votes
/**
 * Checks that the given object serializes to the expected class.
 */
static void checkSerialClassName(Serializable obj, String expected) {
    String cn = serialClassName(obj);
    if (!cn.equals(expected))
        throw new RuntimeException(obj.getClass() + " serialized as " + cn
            + ", expected " + expected);
}
 
Example 7
Project: openjdk-jdk10   File: ObjectStreamTest.java   View Source Code Vote up 5 votes
/**
 * Check ObjectStreamClass facts match between core serialization and CORBA.
 *
 * @param value
 */
@Test(dataProvider = "Objects")
void factCheck(Serializable value) {
    Class<?> clazz = value.getClass();
    java.io.ObjectStreamClass sOSC = java.io.ObjectStreamClass.lookup(clazz);
    java.io.ObjectStreamField[] sFields = sOSC.getFields();
    com.sun.corba.se.impl.io.ObjectStreamClass cOSC = corbaLookup(clazz);
    com.sun.corba.se.impl.io.ObjectStreamField[] cFields = cOSC.getFields();

    Assert.assertEquals(sFields.length, cFields.length, "Different number of fields");
    for (int i = 0; i < sFields.length; i++) {
        Assert.assertEquals(sFields[i].getName(), cFields[i].getName(),
                "different field names " + cFields[i].getName());
        Assert.assertEquals(sFields[i].getType(), cFields[i].getType(),
                "different field types " + cFields[i].getName());
        Assert.assertEquals(sFields[i].getTypeString(), cFields[i].getTypeString(),
                "different field typestrings " + cFields[i].getName());
    }

    Assert.assertEquals(baseMethod("hasReadObjectMethod", sOSC, (Class<?>[]) null),
            corbaMethod("hasReadObject", cOSC, (Class<?>[]) null),
            "hasReadObject: " + value.getClass());

    Assert.assertEquals(baseMethod("hasWriteObjectMethod", sOSC, (Class<?>[]) null),
            corbaMethod("hasWriteObject", cOSC, (Class<?>[]) null),
            "hasWriteObject: " + value.getClass());

    Assert.assertEquals(baseMethod("hasWriteReplaceMethod", sOSC, (Class<?>[]) null),
            corbaMethod("hasWriteReplaceMethod", cOSC, (Class<?>[]) null),
            "hasWriteReplace: " + value.getClass());

    Assert.assertEquals(baseMethod("hasReadResolveMethod", sOSC, (Class<?>[]) null),
            corbaMethod("hasReadResolveMethod", cOSC, (Class<?>[]) null),
            "hasReadResolve: " + value.getClass());

    Assert.assertEquals(baseMethod("getSerialVersionUID", sOSC, (Class<?>[]) null),
            corbaMethod("getSerialVersionUID", cOSC, (Class<?>[]) null),
            "getSerialVersionUID: " + value.getClass());

}
 
Example 8
Project: alfresco-repository   File: DefaultPropertyTypeConverter.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 */
public PersistedType getPersistentType(Serializable value)
{
    ParameterCheck.mandatory("value", value);
    
    Class<?> clazz = value.getClass();
    PersistedType type = persistenceMapping.get(clazz);
    if (type != null)
    {
        // MNT-17523: Loss of information, field values truncated
        if (value instanceof String)
        {
            if (((String) value).length() > SchemaBootstrap.getMaxStringLength())
            {
                return PropertyValueEntity.PersistedType.SERIALIZABLE;
            }
        }
        return type;
    }
    // Before we give up, check if it is constructable
    if (isConstructable(value))
    {
        // It'll just be given back as a class name i.e. a CONSTRUCTABLE
        return PersistedType.CONSTRUCTABLE;
    }
    else if (value instanceof Enum<?>)
    {
        return PersistedType.ENUM;
    }
    else
    {
        // Check if there are converters to and from well-known types, just in case
        if (DefaultTypeConverter.INSTANCE.getConverter(clazz, Long.class) != null &&
                DefaultTypeConverter.INSTANCE.getConverter(Long.class, clazz) != null)
        {
            return PersistedType.LONG;
        }
        else if (DefaultTypeConverter.INSTANCE.getConverter(clazz, String.class) != null &&
                DefaultTypeConverter.INSTANCE.getConverter(String.class, clazz) != null)
        {
            return PersistedType.STRING;
        }
        // No hope of doing anything useful other than storing it
        return PersistedType.SERIALIZABLE;
    }
}
 
Example 9
Project: alfresco-repository   File: PropertyValueDAOImpl.java   View Source Code Vote up 4 votes
@Override
protected PropertyValueEntity findPropertyValueByValue(Serializable value)
{
    // Get the actual type ID
    Class<?> clazz = (value == null ? Object.class : value.getClass());
    Pair<Long, Class<?>> clazzPair = getPropertyClass(clazz);
    if (clazzPair == null)
    {
        // Shortcut: There are no properties of this type
        return null;
    }
    Long actualTypeId = clazzPair.getFirst();
    
    // Construct the search parameters
    PropertyValueEntity queryEntity = new PropertyValueEntity();
    queryEntity.setValue(value, converter);
    queryEntity.setActualTypeId(actualTypeId);
    
    // How would it be persisted?
    PersistedType persistedType = queryEntity.getPersistedTypeEnum();
    Short persistedTypeId = queryEntity.getPersistedType();
    
    // Query based on the the persistable value type
    String query = null;
    Object queryObject = queryEntity;

    // Handle each persisted type individually

    switch (persistedType)
    {
    case NULL:
    case LONG:
        query = SELECT_PROPERTY_VALUE_BY_LOCAL_VALUE;
        break;
    case DOUBLE:
        query = SELECT_PROPERTY_VALUE_BY_DOUBLE_VALUE;
        break;
    case CONSTRUCTABLE:
        // The string value is the name of the class (e.g. 'java.util.HashMap')
    case ENUM:
        // The string-equivalent representation
    case STRING:
        // It's best to query using the CRC and short end-value
        query = SELECT_PROPERTY_VALUE_BY_STRING_VALUE;
        queryObject = new PropertyStringQueryEntity(
                persistedTypeId,
                actualTypeId,
                queryEntity.getStringValue());
        break;
    case SERIALIZABLE:
        // No query
        break;
    default:
        throw new IllegalStateException("Unhandled PersistedType value: " + persistedType);
    }
    
    // Now query
    PropertyValueEntity result = null;
    if (query != null)
    {
        // Uniqueness is guaranteed by the tables, so we get one value only
        result = template.selectOne(query, queryObject);
    }
    
    // Done
    return result;
}
 
Example 10
Project: alfresco-repository   File: PropertyValueDAOImpl.java   View Source Code Vote up 4 votes
private PropertyValueEntity createPropertyValueInternal(Serializable value)
{
    // Get the actual type ID
    Class<?> clazz = (value == null ? Object.class : value.getClass());
    Pair<Long, Class<?>> clazzPair = getOrCreatePropertyClass(clazz);
    Long actualTypeId = clazzPair.getFirst();
    
    // Construct the insert entity
    PropertyValueEntity insertEntity = new PropertyValueEntity();
    insertEntity.setValue(value, converter);
    insertEntity.setActualTypeId(actualTypeId);
    
    // Persist the persisted value
    switch (insertEntity.getPersistedTypeEnum())
    {
    case DOUBLE:
        Double doubleValue = insertEntity.getDoubleValue();
        Pair<Long, Double> insertDoublePair = getOrCreatePropertyDoubleValue(doubleValue);
        insertEntity.setLongValue(insertDoublePair.getFirst());
        break;
    case STRING:
    case CONSTRUCTABLE:
    case ENUM:
        String stringValue = insertEntity.getStringValue();
        Pair<Long, String> insertStringPair = getOrCreatePropertyStringValue(stringValue);
        insertEntity.setLongValue(insertStringPair.getFirst());
        break;
    case SERIALIZABLE:
        Pair<Long, Serializable> insertSerializablePair = createPropertySerializableValue(value);
        insertEntity.setLongValue(insertSerializablePair.getFirst());
        break;
    case NULL:
    case LONG:
        // Do nothing for these
        break;
    default:
        throw new IllegalStateException("Unknown PersistedType enum: " + insertEntity.getPersistedTypeEnum());
    }
    
    // Persist the entity
    template.insert(INSERT_PROPERTY_VALUE, insertEntity);
    // Done
    return insertEntity;
}
 
Example 11
Project: OpenJSharp   File: CDROutputStream_1_0.java   View Source Code Vote up 4 votes
private void writeRMIIIOPValueType(Serializable object, Class clazz) {
    if (valueHandler == null)
        valueHandler = ORBUtility.createValueHandler(); //d11638

    Serializable key = object;

    // Allow the ValueHandler to call writeReplace on
    // the Serializable (if the method is present)
    object = valueHandler.writeReplace(key);

    if (object == null) {
        // Write null tag and return
        write_long(0);
        return;
    }

    if (object != key) {
        if (valueCache != null && valueCache.containsKey(object)) {
            writeIndirection(INDIRECTION_TAG, valueCache.getVal(object));
            return;
        }

        clazz = object.getClass();
    }

    if (mustChunk || valueHandler.isCustomMarshaled(clazz)) {
        mustChunk = true;
    }

    // Write value_tag
    int indirection = writeValueTag(mustChunk, true, Util.getCodebase(clazz));

    // Write rep. id
    write_repositoryId(repIdStrs.createForJavaType(clazz));

    // Add indirection for object to indirection table
    updateIndirectionTable(indirection, object, key);

    if (mustChunk) {
        // Write Value chunk
        end_flag--;
        chunkedValueNestingLevel--;
        start_block();
    } else
        end_flag--;

    if (valueHandler instanceof ValueHandlerMultiFormat) {
        ValueHandlerMultiFormat vh = (ValueHandlerMultiFormat)valueHandler;
        vh.writeValue(parent, object, streamFormatVersion);
    } else
        valueHandler.writeValue(parent, object);

    if (mustChunk)
        end_block();

    // Write end tag
    writeEndTag(mustChunk);
}
 
Example 12
Project: OpenJSharp   File: CDROutputStream_1_0.java   View Source Code Vote up 4 votes
public void write_value(Serializable object, String repository_id) {

        // Handle null references
        if (object == null) {
            // Write null tag and return
            write_long(0);
            return;
        }

        // Handle shared references
        if (valueCache != null && valueCache.containsKey(object)) {
            writeIndirection(INDIRECTION_TAG, valueCache.getVal(object));
            return;
        }

        Class clazz = object.getClass();
        boolean oldMustChunk = mustChunk;

        if (mustChunk)
            mustChunk = true;

        if (inBlock)
            end_block();

        if (clazz.isArray()) {
            // Handle arrays
            writeArray(object, clazz);
        } else if (object instanceof org.omg.CORBA.portable.ValueBase) {
            // Handle IDL Value types
            writeValueBase((org.omg.CORBA.portable.ValueBase)object, clazz);
        } else if (shouldWriteAsIDLEntity(object)) {
            writeIDLEntity((IDLEntity)object);
        } else if (object instanceof java.lang.String) {
            writeWStringValue((String)object);
        } else if (object instanceof java.lang.Class) {
            writeClass(repository_id, (Class)object);
        } else {
            // RMI-IIOP value type
            writeRMIIIOPValueType(object, clazz);
        }

        mustChunk = oldMustChunk;

        // Check to see if we need to start another block for a
        // possible outer value
        if (mustChunk)
            start_block();

    }
 
Example 13
Project: openjdk-jdk10   File: CDROutputStream_1_0.java   View Source Code Vote up 4 votes
private void writeRMIIIOPValueType(Serializable object, Class clazz) {
    if (valueHandler == null)
        valueHandler = ORBUtility.createValueHandler(); //d11638

    Serializable key = object;

    // Allow the ValueHandler to call writeReplace on
    // the Serializable (if the method is present)
    object = valueHandler.writeReplace(key);

    if (object == null) {
        // Write null tag and return
        write_long(0);
        return;
    }

    if (object != key) {
        if (valueCache != null && valueCache.containsKey(object)) {
            writeIndirection(INDIRECTION_TAG, valueCache.getVal(object));
            return;
        }

        clazz = object.getClass();
    }

    if (mustChunk || valueHandler.isCustomMarshaled(clazz)) {
        mustChunk = true;
    }

    // Write value_tag
    int indirection = writeValueTag(mustChunk, true, Util.getCodebase(clazz));

    // Write rep. id
    write_repositoryId(repIdStrs.createForJavaType(clazz));

    // Add indirection for object to indirection table
    updateIndirectionTable(indirection, object, key);

    if (mustChunk) {
        // Write Value chunk
        end_flag--;
        chunkedValueNestingLevel--;
        start_block();
    } else
        end_flag--;

    if (valueHandler instanceof ValueHandlerMultiFormat) {
        ValueHandlerMultiFormat vh = (ValueHandlerMultiFormat)valueHandler;
        vh.writeValue(parent, object, streamFormatVersion);
    } else
        valueHandler.writeValue(parent, object);

    if (mustChunk)
        end_block();

    // Write end tag
    writeEndTag(mustChunk);
}
 
Example 14
Project: openjdk-jdk10   File: CDROutputStream_1_0.java   View Source Code Vote up 4 votes
public void write_value(Serializable object, String repository_id) {

        // Handle null references
        if (object == null) {
            // Write null tag and return
            write_long(0);
            return;
        }

        // Handle shared references
        if (valueCache != null && valueCache.containsKey(object)) {
            writeIndirection(INDIRECTION_TAG, valueCache.getVal(object));
            return;
        }

        Class clazz = object.getClass();
        boolean oldMustChunk = mustChunk;

        if (mustChunk)
            mustChunk = true;

        if (inBlock)
            end_block();

        if (clazz.isArray()) {
            // Handle arrays
            writeArray(object, clazz);
        } else if (object instanceof org.omg.CORBA.portable.ValueBase) {
            // Handle IDL Value types
            writeValueBase((org.omg.CORBA.portable.ValueBase)object, clazz);
        } else if (shouldWriteAsIDLEntity(object)) {
            writeIDLEntity((IDLEntity)object);
        } else if (object instanceof java.lang.String) {
            writeWStringValue((String)object);
        } else if (object instanceof java.lang.Class) {
            writeClass(repository_id, (Class)object);
        } else {
            // RMI-IIOP value type
            writeRMIIIOPValueType(object, clazz);
        }

        mustChunk = oldMustChunk;

        // Check to see if we need to start another block for a
        // possible outer value
        if (mustChunk)
            start_block();

    }