Java type casting interesting query

In java semantics
1) float var1=10.5; // is wrong it should be written as
float var1=(float)10.5; //type casting->double to float
or
float var1=10.5f; //type casting
but
2) byte var2=10; // here int to byte type casting should be there according to previous eg.
But this is correct.
Why the 2nd one is correct???

>
I suspect the reason is, that the compiler can check whether it will fit in the second case.
You can't accidentally type
byte b = 128;Whereas with floating point numbers you could accidentally be losing precision, imagining that you're using doubles, when in fact you are using floats. So the extra cast is needed so you understand you're losing precision.

Similar Messages

  • Could not type cast in java embedding

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    org.xml.sax.InputSource in = (org.xml.sax.InputSource) getVariableData("Invoke_1_getRoutingAndFrameJumpers_OutputVariable","getRoutingAndFrameJumpersResponse");
    Document doc = db.parse(in);
    In the above code I am trying to type cast the variable getRoutingAndFrameJumpersResponse into org.xml.sax.InputSource so that i can parse.
    I am not getting any error during compilation
    but I am unable to type cast some run time error is coming in the line were I am type casting but I am not able to see the runtime error.
    How can I see the runtime error in java embedding, how to type cast a variable into xml so that I can parse it.

    Hi Arun,
    Could you try using the bpelx:rename extension in an assign activity enables a BPEL process to rename an element through use of XSD type casting.
    <bpel:assign>
    <bpelx:rename elementTo="QName1"? typeCastTo="QName2"?>
    <bpelx:target variable="ncname" part="ncname"? query="xpath_str" />
    </bpelx:rename>
    </bpel:assign>
    Cheers
    A

  • Type casting in Java

    Hi,
    Can we do explicit type casting vigorously in a java class? Im in a situation that i've to do explicit casting 40 to 50 times in a class. Is there any overhead for JVM or any performance issue with this?

    Why do you cast so often? It's sounds like a weird design. Casting is pretty cheap.
    Kaj

  • Java Types Conversting & Casting .

    Hi All !
    Really i do have two questions regarding Java Type Conversion and Casting
    and hope i would find (good) answers :
    [Q1:]
    why it's legal to convert(implicitly) from ( long --> float ) and this is
    said to be a widening conversion even if the size of long is longer than float
    and hence there a possible loss of information ?
    [Q2:]
    why it's legal to cast(explicitly) from ( byte --> char ) and how compiler will deal
    with byte as singed and char as unsigned during type casting (this is said to be
    a narrowing converstion and it is really is ) ?
    for [Q2:] i did the follwing code :
    public class TestNarw
         public TestNarw()
              byte bBefore=-100; // change this value to whatever negative number that is to fit in a byte.
              char c=(char)bBefore;
              byte bAfter=(byte)c;
              System.out.println(bBefore);
              System.out.println(c);
              System.out.println(bAfter);
         public static void main(String args[])
              new TestNarw();
               the SURPRISE on the code above is that the output is :
    -100
    -100
    and when i change the value of "bBefore" to any negative number that is to fit in a
    byte it (e.g: -10) it gives the same value for the variable "c" (character)which is ASCII "63" ="?"
    but when i test it with a suitable postive number , it works fine and the character (c) represents that number
    so how it deals with converstion from negative byte to char ?
    Thanks ...

    Q1: you can always cast between primitive types (numbers, not boolean). The only problem is you lose precision in certain directions. A long to float isn't necessarily going to change the value, but it really depends on the long value. If it's out of range of float, it'll basically be wrapped around to the negative side. (at least that's what long to int would do, not sure if float or double behave different in that regard).
    Q2: The value -100 converted to a char would probably be 65436, which prints as "?" because DOS can't print that character. Then when you cast back, 65436 is out of range for a byte, so it rolls back around to -100.
    Try this:
    byte b = 127;
    System.out.println(b);
    System.out.println((byte)b+1);
    System.out.println((byte)0xFF); // 255 in hex
    It'll print 127, then -128, then -1. When you go out of range, it just wraps around. For this reason, you often have to be carefull what size you store things as.

  • Dynamic [Runtime] type casting in Java

    Hello,
    This is my requirement.
    I have a method that takes class name as a parameter.
    Ex:
    Object myMethod(String classname){
    Object xyz = getObject(); //userdefine method which returns some object
    /*<b>I need to typecast above object with the class name passed as the method parameter</b>*/
    /*<b>How can i type cast this object</b>*/
    Object obj = (classname) xyz;
    return obj;
    In the above example, how can i dynamically typecast the object with class whose name is passed as the method parameter?

    Hello,
    This is my requirement.
    I have a method that takes class name as a parameter.
    Ex:
    Object myMethod(String classname){
    Object xyz = getObject(); //userdefine method which
    returns some object
    /*<b>I need to typecast above object with the class
    name passed as the method parameter</b>*/
    /*<b>How can i type cast this object</b>*/
    Object obj = (classname) xyz;
    return obj;
    In the above example, how can i dynamically typecast
    the object with class whose name is passed as the
    method parameter?Perhaps a little more background on the project (what you are trying to do) will help the experts here answer?
    /*with a class that takes a noarg constructor*/
    public Object getObject(String classname) throws Exception
      //might want to get a bit more specific with which exceptions it will throw
      return Class.forName(classname).newInstance();
    }Do I think this sometimes is indicative (perhaps even more often than not), of a possible design flaw? Yes..
    It gets a little trickier if you have constructors (you have to create a Class object representing the string with the .forName(..) ..and then use some reflection to determine constructors and then a bit of logic to determine which of those to use...)
    ~Dave

  • DataNavigator: numeric type cast

    I have a simple data form of jTextField1, jTextField2 and TextField3.
         jTextField1's document = nBCachedRowSet1: id (integer, primary key)
         jTextField2's document = nBCachedRowSet1: name (string type)
         jTextField3's document = nBCachedRowSet1: price (numeric type)
    I'm using DataNavigator to manipulate all records.
    The problem occured when I edit jTextField2 (name) and update it.
    The error message is ...
    ERROR: Unable to identify an operator '=' for types 'numeric' and 'double precision'
    You will have to retype this query using an explicit cast
    java.sql.SQLException: acceptChanges Failed
    at sun.jdbc.rowset.CachedRowSet.acceptChanges(CachedRowSet.java:791)
    at org.netbeans.lib.sql.NBCachedRowSet.acceptChangesInternal(NBCachedRowSet.java:712)
    This message told me to cast NUMERIC type BUT I have no idea.
    HOW to cast
    WHERE to code
    WHAT type to cast to ?

    private void initComponents() {
    connectionSource1 = new org.netbeans.lib.sql.ConnectionSource();
    try {
    nBCachedRowSet1 = new org.netbeans.lib.sql.NBCachedRowSet();
    } catch (java.sql.SQLException e1) {
    e1.printStackTrace();
    dataNavigator1 = new org.netbeans.lib.sql.DataNavigator();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    connectionSource1.setDatabase("jdbc:postgresql://localhost/drugstore004");
    connectionSource1.setDriver("org.postgresql.Driver");
    connectionSource1.setPassword("028a061f882763ad48ddbc977f45e2eca7c8cc685ab9", true);
    connectionSource1.setUsername("Sup");
    nBCachedRowSet1.setCommand("select * from trade");
    nBCachedRowSet1.setConnectionSource(connectionSource1);
    try {
    nBCachedRowSet1.setTableName("trade");
    } catch (java.sql.SQLException e1) {
    e1.printStackTrace();
    nBCachedRowSet1.addInsertRowListener(new org.netbeans.lib.sql.InsertRowListener() {
    public void rowInserted(javax.sql.RowSetEvent evt) {
    nBCachedRowSet1RowInserted(evt);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    dataNavigator1.setRowSet(nBCachedRowSet1);
    getContentPane().add(dataNavigator1, java.awt.BorderLayout.NORTH);
    jTable1.setModel(new org.netbeans.lib.sql.models.TableModel(nBCachedRowSet1, new org.netbeans.lib.sql.models.TableModel.Column[] {
    new org.netbeans.lib.sql.models.TableModel.Column("id", "Id", false),
    new org.netbeans.lib.sql.models.TableModel.Column("name", "Name", true),
    new org.netbeans.lib.sql.models.TableModel.Column("admin", "Admin", true),
    new org.netbeans.lib.sql.models.TableModel.Column("formular", "Formular", true),
    new org.netbeans.lib.sql.models.TableModel.Column("company", "Company", true),
    new org.netbeans.lib.sql.models.TableModel.Column("price", "Price", true),
    new org.netbeans.lib.sql.models.TableModel.Column("addiction", "Addiction", true),
    new org.netbeans.lib.sql.models.TableModel.Column("minimum", "Minimum", true),
    new org.netbeans.lib.sql.models.TableModel.Column("min_unit", "Min unit", true),
    new org.netbeans.lib.sql.models.TableModel.Column("unit_size", "Unit size", true),
    new org.netbeans.lib.sql.models.TableModel.Column("measure_unit", "Measure unit", true),
    new org.netbeans.lib.sql.models.TableModel.Column("form", "Form", true),
    new org.netbeans.lib.sql.models.TableModel.Column("shape", "Shape", true),
    new org.netbeans.lib.sql.models.TableModel.Column("life_span", "Life span", true),
    new org.netbeans.lib.sql.models.TableModel.Column("priority", "Priority", true),
    new org.netbeans.lib.sql.models.TableModel.Column("picture", "Picture", true),
    new org.netbeans.lib.sql.models.TableModel.Column("register", "Register", true),
    new org.netbeans.lib.sql.models.TableModel.Column("barcode", "Barcode", true),
    new org.netbeans.lib.sql.models.TableModel.Column("verifydate", "Verifydate", true),
    new org.netbeans.lib.sql.models.TableModel.Column("remark_ds", "Remark ds", true),
    new org.netbeans.lib.sql.models.TableModel.Column("remark_mk", "Remark mk", true),
    new org.netbeans.lib.sql.models.TableModel.Column("remark_db", "Remark db", true)
    jTable1.setSelectionModel(new org.netbeans.lib.sql.models.SQLListSelectionModel (nBCachedRowSet1));
    jScrollPane1.setViewportView(jTable1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    pack();
    All code are created by "JDBC Application Wizard" (Sun One Studio 4 Community Edition).
    This is table "trade" structure (PostGreSQL)
    drugstore004=# \d trade
    Table "trade"
    Column | Type | Modifiers
    id | integer | not null default nextval('"trade_id_seq"'::text)
    name | character varying(255) | not null
    admin | integer | not null default 1
    formular | integer | not null default 1
    company | integer | not null default 1
    price | numeric(7,2) |
    addiction | smallint |
    minimum | smallint |
    min_unit | integer | not null default 1
    unit_size | smallint |
    measure_unit | integer | not null default 1
    form | integer | not null default 1
    shape | integer | not null default 1
    life_span | smallint |
    priority | integer | not null default 1
    picture | character varying(100) |
    register | character varying(50) |
    barcode | character varying(50) |
    verifydate | date |
    remark_ds | character varying(255) |
    remark_mk | character varying(255) |
    remark_db | character varying(255) |
    Primary key: trade_pkey
    Unique keys: trade_name_key
    Triggers: RI_ConstraintTrigger_113874,
    RI_ConstraintTrigger_113880,
    RI_ConstraintTrigger_113886,
    RI_ConstraintTrigger_113892,
    RI_ConstraintTrigger_113898,
    RI_ConstraintTrigger_113904,
    RI_ConstraintTrigger_113910,
    RI_ConstraintTrigger_113921,
    RI_ConstraintTrigger_113923,
    RI_ConstraintTrigger_113942,
    RI_ConstraintTrigger_113944,
    RI_ConstraintTrigger_113957,
    RI_ConstraintTrigger_113959,
    RI_ConstraintTrigger_113966,
    RI_ConstraintTrigger_113968
    drugstore004=#
    When I edit column "name" (some record where column "price" is null), their is not error.
    But when I edit column "name" where "price" have some price data in it, .... the same error as shown above has come.
    (No Trigger involved in this test because I just add some characters in column "name")
    Some code should be add in "RowChanged" to do some type casting for column "price" but....how?

  • Help needed in data type casting

    I have a java program which will receive data and its type in the String format. During program execution, the data in the String data has to be converted into the respective data type and assigned to a variable of that data type so that it could be used in the program. Programmer may not know the type of data that the value has to be converted into.
    I really got struck up with this. This is a RMI application and one process node is sending the data to another node in the String format and the type of data it should get converted into so that it can be converted into the respective type and used for computation.
    Can you understand what I am asking for ....if you can pls help and it is highly appreciated

    I dont know whether i ahve expressed it correctly
    look at this code
    dataPacket sendtoNode = send.senDatatoNode(inputReq);
    String recnodnum = sendtoNode.nodeNum;
    String recvarnum = sendtoNode.varNum;
    String recvartype = sendtoNode.dataType;
    String recvalvalue     = sendtoNode.dataVal;
    int num;     int type;
    double result;
    // here in this case the result variable type is double
    if (recvartype.equals("int")){
              type = 1;
         result = Integer.parseInt(recvalvalue); will pose problem
         else
         if (recvartype.equals("double")){
              type = 2;
              result = Double.parseDouble(recvalvalue);
         else
         if(recvartype.equals("float")){
              type =3;
              result = Float.parseFloat(recvalvalue); will pose problem
         else
         if(recvartype.equals("Boolean")){
              if ((recvalvalue.equals("true")) || (recvalvalue.equals("TRUE")))
              type = 4;
              result = Boolean.parseBoolean(recvalvalue); will pose problem
         else
         if(recvartype.equals("char")){
              type = 5;
              result = (char)recvalvalue; will pose problem
    else
    if(recvartype.equals("String")){
         type = 6;
              result = recvalvalue; will pose problem
         else
         if(recvartype.equals("byte")){
              type = 7;
              result = Byte.parseByte(recvalvalue); will pose problem
         else
         if(recvartype.equals("long")){
              type = 8;
              result = Long.parseLong(recvalvalue); will pose problem
         else
         if(recvartype.equals("short")){
              type = 9;
              result = Short.parseShort(recvalvalue); will pose problem
         //forvarval varvalue = new forvarval();
         //varvalue.forvarval(recvartype, recvalvalue);
    // this has to be done after sorting the problem of type casting string result = recvalvalue;
    //result = value; //<this will surely give me a problem as i m assigning string to double>??
    send.host(result);
    System.out.println("result received and the result is " +recvalvalue );
    now i need to assign the converted string in to a variable and use in the compuation ..thts where the challenge n not in teh conversion process...

  • Mapping Java Types to XML Types

    Hi, I have a small doubt in web services,
    1)  how a java data type can match with xml data type in wsdl,
    2)  how and where the java program can find the matching java
        data type to xml data type and vice versa
    3)  whether any mechanism is available for this data conversion?
    4)  where can i find that one?
    Please advice me
    Regards
    Marimuthu.N

    Hi Marimuthu.N,
    My answers for your question, Kindly let me know if you need some more inputs.
    +1) how a java data type can match with xml data type in wsdl,+
    In SOAP 1.1 you have the following data types which is in XSD(XML Schema Definition), the same data type is also available in Java. For example (string, normalizedstring in xml is available as java.lang.String)
    The complete list can be found in the table below.
    XSD to Java Mapping.
    XSD Type--------------------------------Java Type
    base64Binary----------------------------byte[]
    hexBinary---------------------------------byte[]
    boolean------------------------------------Boolean
    byte-----------------------------------------Byte
    dateTime----------------------------------java.util.Calendar
    date-----------------------------------------java.util.Calendar
    time-----------------------------------------java.util.Calendar
    decimal------------------------------------java.math.BigDecimal
    double-------------------------------------Double
    float-----------------------------------------Float
    hexBinary---------------------------------byte[]
    int--------------------------------------------Int
    unsignedShort---------------------------Int
    integer--------------------------------------java.math.BigInteger
    long------------------------------------------Long
    unsignedInt-------------------------------Long
    QName-------------------------------------javax.xml.namespace.QName
    short----------------------------------------Short
    unsignedByte---------------------------Short
    string---------------------------------------java.lang.String
    anySimpleType-------------------------java.lang.String
    +2) how and where the java program can find the matching java+
    data type to xml data type and vice versa
    Here is my WSDL which has a method getHello --> Pass Input as String --> Get Response as String.
    <?xml version="1.0" encoding="UTF-8"?>
    <wsdl:definitions targetNamespace="http://zackria.googlepages.com" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://zackria.googlepages.com" xmlns:intf="http://zackria.googlepages.com" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <!--WSDL created by Apache Axis version: 1.4
    Built on Apr 22, 2006 (06:55:48 PDT)-->
    <wsdl:types>
      <schema elementFormDefault="qualified" targetNamespace="http://zackria.googlepages.com" xmlns="http://www.w3.org/2001/XMLSchema">
       <element name="getHello">
        <complexType>
         <sequence>
          <element name="s" type="xsd:string"/>
         </sequence>
        </complexType>
       </element>
       <element name="getHelloResponse">
        <complexType>
         <sequence>
          <element name="getHelloReturn" type="xsd:string"/>
         </sequence>
        </complexType>
       </element>
      </schema>
    </wsdl:types>
       <wsdl:message name="getHelloResponse">
          <wsdl:part element="impl:getHelloResponse" name="parameters"/>
       </wsdl:message>
       <wsdl:message name="getHelloRequest">
          <wsdl:part element="impl:getHello" name="parameters"/>
       </wsdl:message>
       <wsdl:portType name="Test">
          <wsdl:operation name="getHello">
             <wsdl:input message="impl:getHelloRequest" name="getHelloRequest"/>
             <wsdl:output message="impl:getHelloResponse" name="getHelloResponse"/>
          </wsdl:operation>
       </wsdl:portType>
       <wsdl:binding name="TestSoapBinding" type="impl:Test">
          <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
          <wsdl:operation name="getHello">
             <wsdlsoap:operation soapAction=""/>
             <wsdl:input name="getHelloRequest">
                <wsdlsoap:body use="literal"/>
             </wsdl:input>
             <wsdl:output name="getHelloResponse">
                <wsdlsoap:body use="literal"/>
             </wsdl:output>
          </wsdl:operation>
       </wsdl:binding>
       <wsdl:service name="TestService">
          <wsdl:port binding="impl:TestSoapBinding" name="Test">
             <wsdlsoap:address location="http://localhost:8080/TestWebService/services/Test"/>
          </wsdl:port>
       </wsdl:service>
    </wsdl:definitions>I use apache axis for the client side code. I also suggest to start using this to get quickly into SOA(Service Oriented Architecture)
    package com.googlepages.zackria;
    import org.apache.axis.client.Call;
    import org.apache.axis.client.Service;
    import javax.xml.namespace.QName;
    * TestClient for Webservice
    * @author $author$Mohammed Zackria
    * @version $Revision$1.00
    public class TestClient {
         * main method
         * @param args pass nothing as far now
        public static void main(String[] args) {
            try {
                String endpoint = "http://localhost:8080/TestWebService/services/Test";
                Service service = new Service();
                Call call = (Call) service.createCall();
                call.setTargetEndpointAddress(new java.net.URL(endpoint));
                call.setOperationName(new QName("http://zackria.googlepages.com", "getHello"));
                //String Conversion
                String ret = (String) call.invoke(new Object[] { "Zack" });
                System.out.println("Sent 'Zack', got '" + ret + "'");
            } catch (Exception e) {
                System.err.println(e.toString());
    }+3) whether any mechanism is available for this data conversion?+
    Check the above code which has the following portion
    //String Conversion
    String ret = (String) call.invoke(new Object[] { "Zack" });
    By default APACHE Axis returns Object Array which can be Casted to your WSDL defined data type.
    +4) where can i find that one?+
    [Eclipse Webservice|http://www.eclipse.org/webtools/jst/components/ws/1.5/tutorials/BottomUpWebService/BottomUpWebService.html]
    Hope this helps out, Kindly Let me know if you need some more or if i have not answered your question.
    Regards,
    Zack
    Edited by: zack on Nov 22, 2008 1:47 PM
    Edited by: zack on Nov 22, 2008 1:49 PM

  • Type cast exception

    Hi Guys,
    I am pretty new at generics and have started reading all material available online. Shown below is the API that I am using
    package api;
    public interface CS<C extends MyConfig> extends S {
    package api;
    public interface MyConfig {
    package api;
    public interface MySession {     
         public <C extends MyConfig, T extends ResourceContainer<? extends C>>
         T createContainer(CS<C> aPredefinedConfig);
    package api;
    public interface NC extends ResourceContainer<NCC>  {
    package api;
    public interface NCC extends MyConfig {
    package api;
    import java.io.Serializable;
    public interface ResourceContainer <T extends MyConfig> extends Serializable {
    package api;
    public interface S {
         public abstract boolean equals(Object other);
         public abstract int hashCode();
         public abstract String toString();
    }And below is my implementation
    package impl;
    import api.NC;
    public class NCImpl implements NC {
    package impl;
    import api.CS;
    import api.MyConfig;
    import api.MySession;
    import api.ResourceContainer;
    public class MySessionImpl implements MySession {
         public <C extends MyConfig, T extends ResourceContainer<? extends C>> T createContainer(
                   CS<C> predefinedConfig) {
              NCImpl ncimpl = new NCImpl();
              return ncimpl; //Error Type mismatch: cannot convert from NCImpl to T
    }As shown above I get error at line 'return ncimpl' But NCImpl implements the NC which extends ResourceContainer<NCC> so shouldn't it be capable of Type casting to T or I am missing something.
    Thanks a lot for your response in advance

    continuation of stack trace .................
    [INFO] ------------------------------------------------------------------------
    [ERROR] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Compilation failure
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    [INFO] ------------------------------------------------------------------------
    [INFO] Trace
    org.apache.maven.BuildFailureException: Compilation failure
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:579)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:499)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:478)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:330)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:291)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:287)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    at org.apache.maven.plugin.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:516)
    at org.apache.maven.plugin.CompilerMojo.execute(CompilerMojo.java:114)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:451)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:558)
    ... 16 more
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 5 seconds
    [INFO] Finished at: Thu Feb 12 10:39:43 IST 2009
    [INFO] Final Memory: 14M/81M
    [INFO] ------------------------------------------------------------------------
    [abhayani@localhost GenericsTest]$

  • Type Casting Loaded Swf

    I'm having trouble type casting an MXML created swf as in I
    can't seem to get it to work.
    Here is what I'm doing:
    1. Created a LoaderTest.swf that loads AppToLoad.swf
    2. Made AppToLoad implement ISomeInterface
    3. Once AppToLoad.swf is loaded in LoaderTest.swf, attempt to
    type
    cast it as ISomeInterface
    Code (all code is in the same root package):
    <!-- Begin ISomeInterface -->
    package
    public interface ISomeInterface
    function doSomething():void;
    <!-- End ISomeInterface -->
    <!-- Begin AppToLoad -->
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" implements="ISomeInterface">
    <mx:Script>
    <![CDATA[
    private var myInterface:ISomeInterface;
    public function doSomething():void
    trace("doSomething");
    ]]>
    </mx:Script>
    </mx:Application>
    <!-- End AppToLoad -->
    <!-- Begin LoaderTest -->
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute" applicationComplete="start()">
    <mx:Script>
    <![CDATA[
    import mx.managers.SystemManager;
    private var ldr:Loader;
    private function start():void
    ldr = new Loader();
    var ldrContext:LoaderContext = new LoaderContext(false,
    ApplicationDomain.currentDomain);
    ldr.contentLoaderInfo.addEventListener(Event.INIT,
    handleLoaded);
    ldr.load(new URLRequest("AppToLoad.swf"), ldrContext);
    private function handleLoaded(e:Event):void
    trace("handleLoaded");
    var content:Object = LoaderInfo(e.target).content;
    trace("content = "+content);
    var typedContent:ISomeInterface = content as ISomeInterface;
    trace("typedContent = "+typedContent);
    var typedApplication:ISomeInterface = (content as
    SystemManager).application as ISomeInterface;
    trace("typedApplication = "+typedApplication);
    ]]>
    </mx:Script>
    </mx:Application>
    <!-- End LoaderTest -->
    Output from running LoaderTest:
    [SWF] C:\EDGE\testFolder\bin-debug\LoaderTest.swf - 555,437
    bytes
    after decompression
    [SWF] C:\EDGE\testFolder\bin-debug\AppToLoad.swf - 554,844
    bytes after
    decompression
    handleLoaded
    content = [object _AppToLoad_mx_managers_SystemManager]
    typedContent = null
    typedApplication = null
    Any idea what I'm doing wrong?
    -JP

    I'd be interested in seeing the solution as well, but a quick
    workaround is to cast it to the unbind operator.
    This is how I've always done it... Maybe you can get it to
    work with implements:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Canvas xmlns:mx="
    http://www.adobe.com/2006/mxml"
    >
    <mx:Script>
    <![CDATA[
    import mx.events.FlexEvent;
    import mx.managers.SystemManager;
    import mx.core.Application;
    // * gets rid of type checking so we can leave strict
    enabled
    [Bindable]public var _appLoaded:*;
    private var load_finish_playlist:int = 0;
    private var load_finish_name:String = "";
    private function
    onCurrentApplicationComplete(oEvent:Event):void
    _appLoaded = Application(oEvent.target.application);
    if(load_finish_playlist > 0) {
    setPlaylist(load_finish_playlist);
    if(load_finish_name != "") {
    setPlayerName(load_finish_name);
    private function onCompleteAppLoader(oEvent:Event):void
    var smAppLoaded:SystemManager =
    SystemManager(oEvent.target.content); //get a ref to the loaded app
    //listen for the application.complete event
    smAppLoaded.addEventListener(FlexEvent.APPLICATION_COMPLETE,
    onCurrentApplicationComplete);
    public function setPlaylist(id:int):void {
    if(_appLoaded) {
    _appLoaded.change_playlist(id);
    } else {
    load_finish_playlist = id;
    public function setPlayerName(name:String):void {
    if(_appLoaded) {
    _appLoaded.set_name(name);
    } else {
    load_finish_name = name;
    public function stopPlayback():void {
    _appLoaded.stop_playback();
    public function startPlayback():void {
    _appLoaded.start_playback();
    ]]>
    </mx:Script>
    <!-- <mx:SWFLoader id="player" x="0" y="0" source="
    http://...../flash/mixplayer3.swf"
    complete="onCompleteAppLoader(event);" trustContent="true"/>
    --> <mx:SWFLoader id="player" x="0" y="0"
    source="@Embed('../assets/Player.swf')"
    complete="onCompleteAppLoader(event);" trustContent="true"/>
    </mx:Canvas>

  • Type Casting Exception

    I have an attribute CategoryId in my VO of type oracle.jbo.domain.Number. I am trying to use the expression of Boolean item in JHS as #{row.CategoryId != 4}
    Here is the generated JSF code:
                          <af:column id="s141NewItem3Col" noWrap="true" width="100"
                                     rowHeader="false">
                            <f:facet name="header">
                              <af:outputLabel value="CAtIDDeq4" showRequired="false"
                                              id="ol18"/>
                            </f:facet>
                            <af:inputText id="s141NewItem3"
                                          value="#{row.CategoryId != 4}"
                                          label="CAtIDDeq4" required="false"
                                          readOnly="#{((pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn']))) or ((!pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn'])))}"></af:inputText>
                          </af:column>I am getting the run time exception as "Can not convert 4 of type class oracle.jbo.domain.Number to class java.lang.Long"
    I am wondering how the row.CategoryId is treated as Long?. PLease advise. Also, will I be able to use type casting expressions in J Headstart/JSF Expression Language?
    Thanks, Pradeep

    I am trying to set disabled property of an item SubCategory dynamically based on CategoryId value. I guess the transient attribute will not work for newly created records as the transient attribute will be null for newly created records before save is performed. However, the expression #{row.bindings.CategoryId.attributeValue.value== 4 ? false : true} is working fine. row.bindings.CategoryId.attributeValue seem to be returning Long and, row.bindings.CategoryId.attributeValue.value might be returning a Number.

  • Type casting for properties accessed in COM Object

    I have a com object that I need to access which provides my a
    list of addresses in an Array. The object give me a property that
    has a count for the number of addresses and then I have a loop that
    calls the property which contains the address details to get each
    individual address each time passing to the property the INDEX
    value on the loop.
    This errors out each time.
    The error I get is
    Error casting an object of type to an incompatible type.
    This usually indicates a programming error in Java, although it
    could also mean you have tried to use a foreign object in a
    different way than it was designed.
    It appears the the variable type of the index is not
    compatible with the property of the component(which is an int).
    IS there some way to type cast the variable used as the index
    for CFLOOP to that of an INT?

    You can try to use the JavaCast("int", myValue) function. It
    works great for Java objects, but I'm not sure how well it will
    work for COM. Worth a try, I guess.
    In your case it would be something like:
    <cfobject type="COM" context="INPROC" action="create"
    name="MR" class="DLLNAME">
    <cfloop from="1" to="#AddressCount#" index="i">
    <cfset VDname = mr.vdsname(JavaCast("int", i))>
    <cfset VDaddress = mr.vdsaddress(JavaCast("int", i))#>
    <cfset VDXML = mr.VDSXML(JavaCast("int", i))>
    </cfloop>

  • Type casting problem in the JSP

    Hi,
    I am type casting an Object variable to a interface Variable. I am not getting any error if i have the same code in the servlet but i am getting ClassCast Exception if i have the same code in the Scriplets part of the JSP.
    The code is as follows
    String strKey = " SomeString";
    Context context = new InitialContext();
    java.lang.Object obj = null;
         obj = context.lookup(strKey);
         ContentBroker objCB = null;
         objCB = (ContentBroker)obj; // Error is happening here
    ContentBroker is an inteface.
    I have included the jar files of ContentBroker in the classpath.
    Can anyone please tell me how to eliminate this error.?
    thanks in advance,
    Saravanan

    In that case it's a classloader issue.
    Since the object is bound in the context, I assume that you have made the class available to your server, and you have the class in WEB-INF/classes or in a jar inside WEB-INF/lib.
    Since they're being loaded by two different classloaders, the classes are seen as different by the JVM, thus the ClassCastException.
    Try removing the class from the web-app and let us know what happens.
    BTW. Which servlet container are you using?

  • How to use Type Casting in JSF Expression Language

    I have an attribute CategoryId in my VO of type oracle.jbo.domain.Number. I am trying to use the expression of Boolean item in JSF as #{row.CategoryId != 4}
    Here is the JSF code:
                          <af:column id="s141NewItem3Col" noWrap="true" width="100"
                                     rowHeader="false">
                            <f:facet name="header">
                              <af:outputLabel value="CAtIDDeq4" showRequired="false"
                                              id="ol18"/>
                            </f:facet>
                            <af:inputText id="s141NewItem3"
                                          value="#{row.CategoryId != 4}"
                                          label="CAtIDDeq4" required="false"
                                          readOnly="#{((pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn']))) or ((!pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn'])))}"></af:inputText>
                          </af:column>I am getting the run time exception as "Can not convert 4 of type class oracle.jbo.domain.Number to class java.lang.Long".
    I am wondering how the row.CategoryId is treated as Long?. PLease advise. Also, will I be able to use type casting expressions in JSF Expression Language?
    Thanks, Pradeep

    use attributeValue
    Try *#{row.bindings.CategoryId.attributeValue != 4}* ?
    Check this thread for details which discusses about the same:
    El expression to disable  or enable
    Thanks,
    Navaneeth

  • Type casting in JAX-RPC

    Hello
    I was trying to do a JAX-RPC application, and I had some problems with type casting. My application worked fine with primitive types, vectors of primitive types, and beans with primitive type properties. But it didn't work with vectors of beans, or ArrayList's of beans... It couldn't deserialize the result on client side... Can anyone help?
    The Java Web Services Tutorial says that JAX-RPC supports beans and vectors, but I had the impression that this is not a "recursive" support, like "beans with vectors" or "vectors of beans"... Does it make sense?
    By the way, I was using a DII client...
    Thanks,
    Alexandre Murakami

    Hello!
    Thanks for the reply! I can't put the code of my application here (because it's quite big and it's from work)... But I followed the dii client example from the Web Services Tutorial...
    I'm trying to do a kind of a general client... The parameters are the URL of the service, the name of the operation, a list of parameters and the return type class.. And it takes the rest of the service information from the WSDL file... About the return type, I take the QName of the return type from the WSDL:
    <message>
    <part name="result" type="...">...
    then I call the call.setReturnType(QName, Class) method. The return type was an array of a very simple bean, something like:
    class Person {
    String name;
    int age;
    public String getName() {...}
    public void setName(...) {...}
    public int getAge() {...}
    public void setAge(...) {...}
    I don't know if the information I put here is enough... but anyway, thanks for the reply!
    Alexandre Murakami

Maybe you are looking for