hey guys
I'm trying to get hold of a StreamConnection

try {
             StreamConnection conn =  ( StreamConnection )  Connector.open ( url ) ; 

        } catch (Exception ex) {
            ex.printStackTrace();
        }

however when i do this i get the following error

java.lang.ClassCastException

According to my know of and google it should compile fine. I've used this in a J2EE project and it works correctly but not in a J2ME???

J2ME (Micro/Mobile Edition) is a limited version of the J2SE (Standard Edition) and definately will not have anything that first available in the J2EE (Enterprise Edition).

See http://java.sun.com/javame/reference/apis.jsp#api and select the link for the appropriate version to see the API docs, and find out what is available.

the exception tells you exactly what's wrong; you can't cast it, because it's not that type

what makes you think that it is a StreamConnection? and why do you need it to be?

The stream connection is dervived from that class and therefore can be an instance of it. The connector class can be casted to any of its child / parents... hence the HTTPConnection instance etc... take a look at my pervious url link

Before assuming anything just do a System.out.println(Connector.open(url).getClass()) and see which class instance are you actually trying to cast.

The example will show you to convert one data type into another data type by using type casting. The step involved in the program are given below- Vector v = new Vector() :-Creates a new vector. Object obj = v.add( i ) :-Adds an integer type to the vector and stores in an object

To avoid this exception we have to add Integer y = new Integer((String)obj) instead of String y = (String)obj.

CastException.java

import java.util.Vector;
 
public class CastException {
 
  public static void main(String[] args) {
   Vector v = new Vector();
   int i = 10;
   Object obj = v.add(i);
   try {
   String y = (String)obj;
   v.add(y);
  } catch (ClassCastException e) {
   System.out.println("Class is really: " + obj.getClass().getName());
   e.printStackTrace();
   }
   }
 }

Output of the program:

java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
 at CastException.main(CastException.java:11)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.