Example usage for java.lang ClassCastException ClassCastException

List of usage examples for java.lang ClassCastException ClassCastException

Introduction

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

Prototype

public ClassCastException(String s) 

Source Link

Document

Constructs a ClassCastException with the specified detail message.

Usage

From source file:anotadorderelacoes.model.Sentenca.java

@Override
public int compareTo(Object o) {
    if (!(o instanceof Sentenca))
        throw new ClassCastException("Erro de comparao entre classes");
    return this.id - ((Sentenca) o).id;
}

From source file:com.doplgangr.secrecy.settings.SettingsFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {//from www . ja  v a  2  s .  co  m
        mFinishListener = (VaultsListFragment.OnFragmentFinishListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement Listener");
    }
}

From source file:edu.berkeley.path.bots.core.Coordinate.java

/**
 * Returns the distance (in meters) between two coordinates belonging to the
 * same system of coordinates, and using the default distance method for
 * this system./*from  w  ww  .j a  v  a 2 s  .com*/
 * 
 * @param otherCoord
 * @return
 */
public double distanceDefaultMethodInMeters(Coordinate otherCoord) {
    if (this.srid() == SRID_CARTESIAN) {
        return this.distanceCartesianInMeters(otherCoord);
    }
    if (this.srid() == 4326) {
        // return this.distanceHaversineInMeters(otherCoord);
        return this.distanceVincentyInMeters(otherCoord);
    }
    throw new ClassCastException("SRID not supported by this function.");
}

From source file:com.mastfrog.scamper.SctpServerAndClientBuilder.java

/**
 * Map a message type to a handler which will receive messages of that type
 *
 * @param type The type/* w w  w .  j  a v  a  2s  . c o  m*/
 * @param handlerType The handler type (will be instantiated by Guice)
 * @return this
 */
public SctpServerAndClientBuilder bind(MessageType type, Class<? extends MessageHandler<?, ?>> handlerType) {
    Checks.notNull("type", type);
    Checks.notNull("handlerType", handlerType);
    if (!MessageHandler.class.isAssignableFrom(handlerType)) {
        throw new ClassCastException("Not a subclass of MessageHandler: " + handlerType);
    }
    for (ProtocolModule.Entry entry : bindings) {
        if (entry.message.equals(type)) {
            throw new ConfigurationError(entry.type + " was already " + "registered for " + type);
        }
    }
    bindings.add(new ProtocolModule.Entry(type, handlerType));
    return this;
}

From source file:com.ebay.erl.mobius.core.model.Tuple.java

/**
 * Get the value of the given column <code>name</code> in
 * the <code>expecting_type</code>.
 * <p>/*ww w . jav  a 2 s  . co  m*/
 * 
 * If the original <code>value</code> is not in the exact
 * same <code>expecting_type</code>, Mobius will try to
 * convert it to the <code>expecting_type</code> and return
 * it.
 * <p>
 * 
 * If the original <code>value</code> is null, then 
 * <code>default_value</code> is returned.
 * 
 * @param expecting_type user specified type for the returned value. 
 * @param name the name of a column within this tuple.
 * @param value the original value of the column <code>name</code>
 * @param default_value if the original value is null, then <code>default_value</code>
 * is returned.
 * @return
 */
protected Object get(byte expecting_type, String name, Object value, Object default_value) {
    byte actual_type = Tuple.getType(value);

    if (expecting_type == Tuple.getType(value)) {
        return value;
    } else {
        // expecting type and actual type are different.         
        if (Tuple.isNumericalType(expecting_type) && Tuple.isNumericalType(actual_type)) {
            if (value == null) {
                return default_value;
            }

            // expecting value and actual value are both numerical type,
            // but not exact the same, perform transformation.
            switch (expecting_type) {
            case BYTE_TYPE:
                return ((Number) value).byteValue();
            case SHORT_TYPE:
                return ((Number) value).shortValue();
            case INTEGER_TYPE:
                return ((Number) value).intValue();
            case LONG_TYPE:
                return ((Number) value).longValue();
            case FLOAT_TYPE:
                return ((Number) value).floatValue();
            case DOUBLE_TYPE:
                return ((Number) value).doubleValue();
            default:
                throw new IllegalArgumentException(
                        String.format("%02X", expecting_type) + " is not numerical type.");
            }
        } else if (expecting_type == STRING_TYPE && actual_type != STRING_TYPE) {
            if (value == null) {
                return default_value;
            }

            LOGGER.trace("Accessing column[" + name + "], the expecting type is ["
                    + Tuple.getTypeString(expecting_type) + "], " + "but actual type is ["
                    + Tuple.getTypeString(actual_type) + "], using toString() to get the value.");
            // expecting type is string, but the actual type is not string, 
            // convert it to string by calling toString().
            return value.toString();
        } else if (Tuple.isDateType(expecting_type) && Tuple.isDateType(actual_type)) {
            // date type, but the expecting type is not the same as the actual type.
            // Ex:, expecting java.sql.Date, but actual is java.sql.Timestamp
            if (value == null) {
                return default_value;
            }

            // use java.util.Date as the actual type would be
            // either java.sql.Date, java.sql.Time or 
            // java.sql.Timestamp.
            java.util.Date actual_value = (java.util.Date) value;

            switch (expecting_type) {
            case Tuple.DATE_TYPE:
                java.sql.Date sqlDate = new java.sql.Date(actual_value.getTime());
                return sqlDate;
            case Tuple.TIME_TYPE:
                java.sql.Time sqlTime = new java.sql.Time(actual_value.getTime());
                return sqlTime;
            case Tuple.TIMESTAMP_TYPE:
                java.sql.Timestamp sqlTimeStamp = new java.sql.Timestamp(actual_value.getTime());
                return sqlTimeStamp;
            default:
                throw new IllegalArgumentException(Tuple.getTypeString(actual_type) + " is not a date type.");
            }

        } else if (Tuple.isDateType(expecting_type) && actual_type == STRING_TYPE) {
            // expecting type is date type, but the actual type is string
            switch (expecting_type) {
            case Tuple.DATE_TYPE:
                java.sql.Date sqlDate = java.sql.Date.valueOf((String) value);
                return sqlDate;
            case Tuple.TIME_TYPE:
                java.sql.Time sqlTime = java.sql.Time.valueOf((String) value);
                return sqlTime;
            case Tuple.TIMESTAMP_TYPE:
                java.sql.Timestamp sqlTimeStamp = java.sql.Timestamp.valueOf((String) value);
                return sqlTimeStamp;
            default:
                throw new IllegalArgumentException(Tuple.getTypeString(actual_type) + " is not a date type.");
            }
        } else if (Tuple.isNumericalType(expecting_type) && actual_type == STRING_TYPE) {
            if (value == null) {
                return default_value;
            }

            // expecting type is numerical, but the actual type is string, 
            // try to convert it into numerical value
            String value_str = (String) value;
            try {
                switch (expecting_type) {
                case BYTE_TYPE:
                    return Byte.parseByte(value_str);
                case SHORT_TYPE:
                    return Short.parseShort(value_str);
                case INTEGER_TYPE:
                    return Integer.parseInt(value_str);
                case LONG_TYPE:
                    return Long.parseLong(value_str);
                case FLOAT_TYPE:
                    return Float.parseFloat(value_str);
                case DOUBLE_TYPE:
                    return Double.parseDouble(value_str);
                default:
                    throw new IllegalArgumentException(
                            String.format("%02X", expecting_type) + " is not numerical type.");
                }
            } catch (NumberFormatException e) {
                throw new NumberFormatException("The value of column[" + name + "] is [" + value_str
                        + "] and cannot be converted into " + Tuple.getTypeString(expecting_type));
            }
        } else if (expecting_type == BOOLEAN_TYPE && actual_type == STRING_TYPE) {
            return Boolean.valueOf((String) value);
        }
        throw new ClassCastException("Column [" + name + "] is " + Tuple.getTypeString(actual_type)
                + ", cannot be converted into " + Tuple.getTypeString(expecting_type));
    }
}

From source file:CalendarUtils.java

/**
 * See the other getCalendarIterator.  Works with an Object, trying
 * to use it as a Date or Calendar.//w w  w  .j a  v  a2s  .  com
 */
public static Iterator getCalendarIterator(Object focus, int rangeStyle) {
    if (focus instanceof Date) {
        return getCalendarIterator((Date) focus, rangeStyle);
    } else if (focus instanceof Calendar) {
        return getCalendarIterator((Calendar) focus, rangeStyle);
    } else {
        throw new ClassCastException("Could not iterate based on " + focus);
    }
}

From source file:com.almende.eve.rpc.jsonrpc.JSONRPC.java

/**
 * Cast a JSONArray or JSONObject params to the desired paramTypes.
 * //from ww w  . j  av  a2 s  .c  om
 * @param params
 *            the params
 * @param annotatedParams
 *            the annotated params
 * @param requestParams
 *            the request params
 * @return the object[]
 */
private static Object[] castParams(final Object realDest, final Object params,
        final List<AnnotatedParam> annotatedParams, final RequestParams requestParams) {

    if (annotatedParams.size() == 0) {
        if (realDest != null) {
            return new Object[] { realDest };
        } else {
            return new Object[0];
        }
    }

    if (params instanceof ObjectNode) {
        // JSON-RPC 2.0 with named parameters in a JSONObject

        if (annotatedParams.size() == 1 && annotatedParams.get(0).getType().equals(ObjectNode.class)
                && annotatedParams.get(0).getAnnotations().size() == 0) {

            // the method expects one parameter of type JSONObject
            // feed the params object itself to it.
            if (realDest != null) {
                return new Object[] { realDest, params };
            } else {
                return new Object[] { params };
            }
        } else {

            final ObjectNode paramsObject = (ObjectNode) params;
            int offset = 0;
            if (realDest != null) {
                offset = 1;
            }
            final Object[] objects = new Object[annotatedParams.size() + offset];
            if (realDest != null) {
                objects[0] = realDest;
            }
            for (int i = 0; i < annotatedParams.size(); i++) {
                final AnnotatedParam p = annotatedParams.get(i);

                final Annotation a = getRequestAnnotation(p, requestParams);
                if (a != null) {
                    // this is a systems parameter
                    objects[i + offset] = requestParams.get(a);
                } else {
                    final String name = getName(p);
                    if (name != null) {
                        // this is a named parameter
                        if (paramsObject.has(name)) {
                            objects[i + offset] = TypeUtil.inject(paramsObject.get(name), p.getGenericType());
                        } else {
                            if (isRequired(p)) {
                                throw new ClassCastException("Required parameter '" + name + "' missing.");
                            } else if (p.getType().isPrimitive()) {
                                // TODO: should this test be moved to
                                // isAvailable()?
                                throw new ClassCastException(
                                        "Parameter '" + name + "' cannot be both optional and "
                                                + "a primitive type (" + p.getType().getSimpleName() + ")");
                            } else {
                                objects[i + offset] = null;
                            }
                        }
                    } else {
                        // this is a problem
                        throw new ClassCastException("Name of parameter " + i + " not defined");
                    }
                }
            }
            return objects;
        }
    } else {
        throw new ClassCastException("params must be a JSONObject");
    }
}

From source file:edu.berkeley.path.bots.core.Coordinate.java

/**
 * This will eventually do something more useful than return the length of
 * the smallest link in dca.streets. It will: This function returns the
 * distance between this Coordinate and otherCoord (in meters) grossly and
 * quickly, always approximating to a shorter distance. This function in
 * intended to be used by heuristics that want a helicopter distance and
 * require that this value is never ever be larger than the length returned
 * by the accurate spheroid distance function. Currently only SRID 4326 is
 * supported.//  w  w  w.j a  v a2s . c o  m
 * 
 * @param otherCoord
 *            to find the distance to.
 * @return in meters a number that is less than or equal to the spheroid
 * @throws ClassCastException
 *             if the <code>srid</code>'s are not 4326.
 */
public double distanceLessThanOrEqualToSpheroidDistanceInMeters(Coordinate otherCoord) {
    if (4326 != this.srid() || 4326 != otherCoord.srid()) {
        throw new ClassCastException("Only SRID 4326 accepted for now.");
    }
    return 2.02117036255978; // Smallest length in dca.streets.
}

From source file:cn.studyjams.s2.sj0132.bowenyan.mygirlfriend.nononsenseapps.notepad.ui.editor.TaskDetailFragment.java

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (dontLoad) {
        return;// w w w .j  a  va 2  s. co m
    }
    try {
        mListener = (TaskEditorCallbacks) getActivity();
    } catch (ClassCastException e) {
        throw new ClassCastException("Activity must implement TaskEditorCallbacks");
    }
}

From source file:com.itemanalysis.psychometrics.rasch.Theta.java

public int compareTo(Object o) {
    if (!(o instanceof Theta))
        throw new ClassCastException("Theta object expected");

    Double otherTheta = ((Theta) o).value();

    if (this.theta > otherTheta)
        return 1;
    if (this.theta < otherTheta)
        return -1;
    return 0;//from  w  ww  .j a  v  a2s. co m
}