Results 1 to 2 of 2
  1. #1
    barney is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default Cast Error Caught (change) Class is really: java.lang.String

    Hi, I was getting a class cast exception in part of my code (using Java 2 sdk 1.4.1). I added an exception handler and the following is the section of the code:

    Java Code:
    Object obj = _secondVector.get(i);
    try{
    Integer y = (Integer)obj;
    _firstVector.set(y.intValue(), "<<<remove>>>");
    }catch(ClassCastException e){
    System.err.println("Cast Error Caught (change)");
    System.err.println("Class is really: " + obj.getClass().getName());
    e.printStackTrace();
    }
    _secondVector is simply of the Vector class. this, i thought returned an Object. However, the exception handler prints out:

    Java Code:
    Cast Error Caught (change)
    Class is really: java.lang.String
    can anyone shed some light on why obj is a String instead of an Object?

    i tried changing the line:

    Java Code:
    Integer y = (Integer)obj;
    to:
    Java Code:
    Integer y = new Integer(obj);
    Because it said that obj was actually a String and there is an Integer constructor with String as the argument, but i get:
    Java Code:
    cannot resolve symbol
    symbol : constructor Integer (java.lang.Object)
    location: class java.lang.Integer
    Integer y = new Integer(obj);
    So now it's telling me that obj is an object, and before that it was a string......
    Thanks.

  2. #2
    henry_78 is offline Member
    Join Date
    Aug 2007
    Posts
    47
    Rep Power
    0

    Default

    Hi,
    To do the casting u have to be sure that the obj is really an Integer Object, otherwise u cant do the casting. I think that your _secondVector contains only string objects, so u cant do the sating from object to Integer, try to do the casting from object to string..Bye.

Similar Threads

  1. Replies: 2
    Last Post: 09-18-2008, 08:30 AM
  2. How to cast an Object into a specific type (Integer/String) at runtime
    By mailtogagan@gmail.com in forum Advanced Java
    Replies: 2
    Last Post: 12-03-2007, 02:04 PM
  3. Error: cannot be applied to (java.lang.String)
    By carl in forum New To Java
    Replies: 1
    Last Post: 08-05-2007, 07:33 AM
  4. Replies: 1
    Last Post: 07-31-2007, 06:52 AM
  5. Can't convert java.lang.String to int.
    By Albert in forum AWT / Swing
    Replies: 2
    Last Post: 07-13-2007, 06:05 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •