Object array type casting?

Hi. I still can't get the hang of array type casting. Is it possible to type caste an array of objects? I tried the following
LabelledPanel[] comp = (LabelledPanel[])(content.getComponents());
in my program and I got the ClassCastException.
Exception occurred during event dispatching:
java.lang.ClassCastException: [Ljava.awt.Component;
LabelledPanel is a descendent of JPanel and getComponents() supposed to return Component[]

java does support casting with arrays. The following code will work:
String [] strings = new String[] { "1", "2" };
Comparable [] comps = (Comparable[])strings;
Object [] objects = (Object [])strings;That is, you can cast following the normal rules of assignment. You are having problems because your casting violates the normal rules of assignment- you're trying to cast a type into a differnt type that it does not extend or implement.
the toArray() in the Collections API really has nothing to do with casting. That method converts the current Collection into an array of the same type. Since all arrays extend java.lang.Object, it returns the new array as an Object, which you then cast into the specific type.
You may want to read the language guidlines on casting if you are having problems with it:
http://java.sun.com/docs/books/jls/second_edition/html/jIX.fm.html
you can also look at the documenation for Class.isAssignableFrom , which explains casting more briefly.

Similar Messages

  • Insertion in Table having Column of object array type

    Hi!
    I want to make an object type and then the VARRAY of the that object type and then make table having column of VARRAY type.
    How can i issue an Insert statement to insert values in columns of VARRAY type .
    I will be thankful.
    regards
    Imran

    See following discussion http://asktom.oracle.com/pls/ask/f?p=4950:8:11071256505039606339::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:1583117527730
    and let's thank again Tom !

  • Retrieved data from database assignd to object array

    Hi all,
    Im new to java. I creat class it has item_name,item_qty,item_price as properties.then i need to create object array type of that class.now i need to assign values to properties in each element of object array from the database.in my database has ITEM table it has data according to that properties of class.how i do this.please tel me .
    thanks in Advanced,

    Harsha_Lasith wrote:
    yes I knew connect to the database using JDBC.but i have not clear understand about instantiate an object of a class using a constructor.please give me some example for those.
    thanks in advance.If you don't know how to use constructors you really should not be trying to use the JDBC. Learn Java first.

  • 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 arrays

    i m reading an array of int from ObjectOutPutStream. can any body tell how do we type cast an object to array ??

    karansha:
    I'm sure you mean you're trying to read in an int[] from an ObjectInputStream that was written to an ObjectOutputStream since you can't read from an OutputStream. Use something like this:
    ObjectInputStream in = <whatever>;
    int[] intArray = (int[])in.readObject();adramolek:
    Why should you use an Integer[] instead of an int[] for serialization? All arrays of primitives -- boolean[], byte[], double[], float[], int[], long[], short[] -- are serializable as is; there is no need to convert them to arrays of their wrapper types simply to serialize them.
    In fact, the output from the following piece of code shows exactly which interfaces are implements by an int[]:
    Class cls = int[].class;
    Class[] interfaces = cls.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        System.out.println(interfaces.getName());
    The output is:
    java.lang.Cloneable
    java.io.SerializableThe output is identical for each of boolean[], byte[], double[], float[], int[], long[], and short[], showing that each type is both serializable [i]and cloneable.
    Shaun                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to overcome: System.InvalidCastException: Unable to cast object of type

    Hi,
    For the database connectivity, we use ODP.Net. In one of the functionality we are trying to bind an array to stored procedures and have it execute for the each iteration of the array as a bulk transaction.
    Not always but, 10% of the times the function has raised the following exception
    System.InvalidCastException: Unable to cast object of type 'System.DateTime[]' to type 'System.IConvertible' .
    Has anyone ever faced such a problem, if someone has a soltuion it would be of great help to me.
    Thanks

    Hi,
    For the database connectivity, we use ODP.Net. In one of the functionality we are trying to bind an array to stored procedures and have it execute for the each iteration of the array as a bulk transaction.
    Not always but, 10% of the times the function has raised the following exception
    System.InvalidCastException: Unable to cast object of type 'System.DateTime[]' to type 'System.IConvertible' .
    Has anyone ever faced such a problem, if someone has a soltuion it would be of great help to me.
    Thanks

  • Is there a way to type cast an array of strings to numbers and back again?

    I'm working on an application where I want to type cast a string like "power supply" into an array of existing numbers. Then sort the existing numbers, and finally convert the casted numbers back into a string so it can be read by the user. In the attachment, you can see my latest attempt with flatten/unflatten data and the 'convert string to byte array'. I can't seem to make this work. Any ideas?
    Thanks - Paul
    Attachments:
    Paul's Temp scan for components.vi ‏56 KB

    OK, here's a quickie (LabVIEW 7.0).
    Simply get the sort key from the 1D array, then build the table.
    Message Edited by altenbach on 10-27-2006 01:34 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    SortedTable.png ‏4 KB
    SortedTable.vi ‏37 KB

  • Splitting and type casting huge string into arrays

    Hello,
    I'm developing an application which is supposed to read measurement files. Files contain I16 and SGL data which is type casted into string. I16 data is data from analog input and SGL is from CAN-bus data in channel form. CAN and analog data is recorded using same scan rate.
    For example, if we have 6 analog channels and 2 CAN channels string will be (A represents analog and C represents CAN):
    A1 A2 A3 A4 A5 A6 C1 C2 A1 A2 A3 A4 A5 A6 C1 C2 A1 A2 .... and so on
    Anyway, I have problems reading this data fast enough into arrays. Most obvious solution to me was to use shift registers and split string in for loop. I created a for loop with two inner for loops. Number of scans to read from string is wired to N terminal of the outermost loop. Shift register is initialized with string read from file.
    First of the inner loops reads analog input data. Number of analog channels is wired to its N terminal. It's using split string to read 2 bytes at a time and then type casts data to I16. Rest of the string is wired to shift register. When every I16 channel from scan is read, rest of the string is passed to shift register of the second for loop.
    Second loop is for reading CAN channels. It's similar to first loop except data is read 4 bytes at a time and type casted to SGL. When every CAN channel from scan is read, rest of the string is passed to shift register of the outermost loop. Outputs of type cast functions are tunneled out of loops to produce 2D arrays.
    This way reading about 500 KB of data can take for example tens of seconds depending on PC and number of channels. That's way too long as we want to read several megabytes at a time.
    I created also an example with one inner loop and all data is type casted to I16. That is extremely fast when compared to two inner loops!
    Then I also made a test with two inner loops where I replaced shift register and split string with string subset. That's also faster than two inner loops + shift register, but still not fast enough. Any improvement ideas are highly appreciated. Shift register example attached (LV 7.1)
    Thanks in advance,
    Jakke Palonen
    Attachments:
    String to I16 and SGL arrays.vi ‏39 KB

    OK, there is clearly room for improvement. I did some timing and my two above suggestions are already about 100x faster than yours. A few teeaks led to a version that is now over 500x faster than the original code.
    A few timings on my rather slow computer (1GHz PIII Laptop) are shown on the front panel. For example with 10000 scans (~160kB data as 6+2) my new fastest version (Reshape II) takes 14 ms versus the original 7200ms! It can do 100000 scans (1.6MB data) in under 200 ms and 1000000 scans (15MB data) in under 2 seconds.
    I am sure the code could be further improved. I recommend the Reshape II algoritm. It is fastest and can deal with variable channel counts. Modify as needed.
    Attached is a LabVIEW 7.1 version of the benchmarking code, containing all algorithms. I have verified that all algorithms produce the same result (with the limitation that the cluster version only works for 6*I16+2*SGL data, of course). Remember that the reshape function is extremely efficient, because it does not move the data in memory. I have some ideas for further improvements, but this should get you going.
    Message Edited by altenbach on 08-05-2005 03:06 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    StringI16SGLCastingTimer.png ‏48 KB
    StringtoI16andSGLArraysMODTimer.vi ‏120 KB

  • Converting object wrapper type array into equivalent primary type array

    Hi All!
    My question is how to convert object wrapper type array into equivalent prime type array, e.g. Integer[] -> int[] or Float[] -> float[] etc.
    Is sound like a trivial task however the problem is that I do not know the type I work with. To understand what I mean, please read the following code -
    //Method signature
    Object createArray( Class clazz, String value ) throws Exception;
    //and usage should be as follows:
    Object arr = createArray( Integer.class, "2%%3%%4" );
    //"arr" will be passed as a parameter of a method again via reflection
    public void compute( Object... args ) {
        a = (int[])args[0];
    //or
    Object arr = createArray( Double.class, "2%%3%%4" );
    public void compute( Object... args ) {
        b = (double[])args[0];
    //and the method implementation -
    Object createArray( Class clazz, String value ) throws Exception {
         String[] split = value.split( "%%" );
         //create array, e.g. Integer[] or Double[] etc.
         Object[] o = (Object[])Array.newInstance( clazz, split.length );
         //fill the array with parsed values, on parse error exception will be thrown
         for (int i = 0; i < split.length; i++) {
              Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
              o[i] = meth.invoke( null, new Object[]{ split[i] });
         //here convert Object[] to Object of type int[] or double[] etc...
         /* and return that object*/
         //NB!!! I want to avoid the following code:
         if( o instanceof Integer[] ) {
              int[] ar = new int[o.length];
              for (int i = 0; i < o.length; i++) {
                   ar[i] = (Integer)o;
              return ar;
         } else if( o instanceof Double[] ) {
         //...repeat "else if" for all primary types... :(
         return null;
    Unfortunately I was unable to find any useful method in Java API (I work with 1.5).
    Did I make myself clear? :)
    Thanks in advance,
    Pavel Grigorenko

    I think I've found the answer myself ;-)
    Never thought I could use something like int.class or double.class,
    so the next statement holds int[] q = (int[])Array.newInstance( int.class, 2 );
    and the easy solution is the following -
    Object primeArray = Array.newInstance( token.getPrimeClass(), split.length );
    for (int j = 0; j < split.length; j++) {
         Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
         Object val = meth.invoke( null, new Object[]{ split[j] });
         Array.set( primeArray, j, val );
    }where "token.getPrimeClass()" return appropriate Class, i.e. int.class, float.class etc.

  • Production Order Error: "Unable to cast COM object of type 'System.__ComObj

    Hi all,
    I have the following code:
    Dim oProdOrders As SAPbobsCOM.Documents
    oProdOrders = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oProductionOrders)
    after the second line I get a system exception: {"Unable to cast COM object of type 'System.__ComObject' to interface type 'SAPbobsCOM.Documents'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{A6DA575B-E105-4585-9F4B-50CC4044EEDD}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))."}     
    If I change document to eg oQuotations it proceeds normally.
    Any Idea?
    Thanks in advance,
    Vangelis

    try it as
    Dim oProdOrders As SAPbobsCOM.ProductionOrders
    oProdOrders = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oProductionOrders)

  • Unable to cast object of type 'Oracle.DataAccess.Types.OracleDecimal'......

    I have some Oracle Tables with sequences for primary key and stored procs in packages to wrap up the insert commands. The sequences field are all declared as NUMBER.
    I also have Datasets based on the tables and a DataAdapter for each package. The Datasets see the primary keys as System.Decimal. The DataAdapter sees the output primary key parameter to the stored procs as OracleDecimal.
    tmp.Parameters.Add(new OracleParameter("P_ID", Oracle.DataAccess.Client.OracleDbType.Decimal, ParameterDirection.Output));
    tmp.Parameters["P_ID"].SourceColumn = "ID";
    When I call the Update on the DataAdapter the update happens on the DB and then I get the following error
    System.ArgumentException : Unable to cast object of type 'Oracle.DataAccess.Types.OracleDecimal' to type 'System.IConvertible'.Couldn't store <231> in ID Column. Expected type is Decimal.
    ----> System.InvalidCastException : Unable to cast object of type 'Oracle.DataAccess.Types.OracleDecimal' to type 'System.IConvertible'.
    If I change the Oracle parameter to Oracle.DataAccess.Client.OracleDbType.Int32 or Oracle.DataAccess.Client.OracleDbType.Int64 it works fine - any ideas why that would be ? I would expect System.Decimal to map to Oracle.DataAccess.Types.OracleDecimal.

    Hi,
    If I change the Oracle parameter to Oracle.DataAccess.Client.OracleDbType.Int32 or Oracle.DataAccess.Client.OracleDbType.Int64 it works fine - any ideas why that would be ? I would expect System.Decimal to map to Oracle.DataAccess.Types.OracleDecimal.
    I'm trying to do the same, but no matter what I do, I get the OracleDecimal error. Parameter is defined as:
    bq. this._adapter.InsertCommand = new global::Oracle.DataAccess.Client.OracleCommand(); \\ this._adapter.InsertCommand.Connection = this.Connection; \\ this._adapter.InsertCommand.CommandText = "INSERT INTO PERSON\r\n                      (ID, SURNAME, NAME, BIRTHCITY, EMSO)\r\nV" + \\ +"ALUES (:ID, :SURNAME, :NAME, :BIRTHCITY, :EMSO) RETURNING ID INTO :ID";+ \\ this._adapter.InsertCommand.CommandType = global::System.Data.CommandType.Text; \\ param = new global::Oracle.DataAccess.Client.OracleParameter(); \\ param.ParameterName = "ID"; \\ param.DbType = global::System.Data.DbType.Int32; \\ param.OracleDbType = global::Oracle.DataAccess.Client.OracleDbType.Int32; \\ param.Direction = global::System.Data.ParameterDirection.Output; \\ param.IsNullable = true; \\ param.SourceColumn = "ID"; \\ this._adapter.InsertCommand.Parameters.Add(param);
    But no luck...

  • Unable to cast object of type OracleXmlType to type XmlDocument

    Hello All:
    I have an Oracle Procedure that is taking an XML Document as an output parameter.
    oCommand.Parameters.Add("errorrecord", OracleDbType.XmlType).Value = System.DBNull.Value;
    oCommand.Parameters["errorrecord"].Direction = System.Data.ParameterDirection.Output;
    When I try to cast this as an XmlDocument so I can set it to my ErrorRecord variable (defined as XmlDocument) and pass it back out of the Web-Service
    ErrorRecord = (XmlDocument)oCommand.Parameters["p_errorrecord"].Value;
    I get the following error: "Unable to cast object of type 'Oracle.DataAccess.Types.OracleXmlType' to type 'System.Xml.XmlDocument'"
    How do I cast / convert the Oracle XMLType back to a .Net XMLDocument to pass out of the function?
    Thanks

    No, I have not tried that yet, but I admit I don't fully understand the syntax in the document posted.
    oCommand.Parameters.Add("p_errorrecord", OracleDbType.XmlType).Value = System.DBNull.Value;
    ErrorRecord = GoCommand.Parameters["errorrecord"].Value; (this is returned as XmlType)
    I don't quite understand the syntax in the posted URL:
    Declaration
    // C#
    public XmlDocument GetXmlDocument();
    How am I to use this to get the XMLDocument?

  • Unable to cast object of type InfoObject to DestinationPlugin

    I have created a web application to show the list of scheduled reports and with their destination Info using Business objects sdk. Locally on my computer i am able to show all the reports and the Ftp information. But when i move this application to QA server the application returns an error with a message.
    "Unable to cast object of type 'CrystalDecisions.Enterprise.InfoObject' to type 'CrystalDecisions.Enterprise.DestinationPlugin"
    I have noticed that the returned type of Object by the query on QA server is of type "InfoObject" and on localbox "CrystalDecisions.Enterprise.Dest.Ftp"
    Query
    Select * from ci_systemobjects where SI_NAME= ''", "CrystalEnterprise.Ftp"
    Assemblies required by application are registered in the GAC with same version and same public token
    Please let me know if anyone has a answer for this casting exception.

    Snippet:
    Dim ftp As New Ftp(infoObject.PluginInterface)
    Dim ftpOptions As New FtpOptions(ftp.ScheduleOptions)
    You wouldn't be doing a direct runtime cast.
    Sincerely,
    Ted Ueda

  • Unable to cast object of type 'System.Xml.XmlText' to type 'System.Xml.XmlE

    Hi All,
    We just migrated from BPC 5.1 to BPC 7.0 SP6. But when we want to run a package in the data manager we get the following error:
    Exception Text **************
    System.InvalidCastException: Unable to cast object of type 'System.Xml.XmlText' to type 'System.Xml.XmlElement'.
       at OSoft.Consumers.DataMgr.PackageModify50.PackageDetail.LoadDetail(String strXMLString)
       at OSoft.Consumers.DataMgr.PackageModify50.PackageDetail.GetPackageDetailfromServer(String strPackageName, String strPackageFilePath, String strTeamID)
       at OSoft.Consumers.DataMgr.PackageModify50.frmMain.PackageListClickEvent(String strPackageID, String strPackageFileName, String strTeamID)
       at OSoft.Consumers.DataMgr.PackageModify50.frmMain.SetStartUp()
       at OSoft.Consumers.DataMgr.PackageModify50.frmMain.frmMain_Load(Object sender, EventArgs e)
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    Any idea?
    Br
    Steven

    Hi,
    If you were running 5.1 version, that would also mean that you were running packages under SQL 2005.
    And if you are now running SQL 2008 with BPC 7.0, you should also review all your customized packages. In fact, BPC tasks in SSIS are not the same between SQL 2005 and SQL 2008.
    In addition, I would recommend to upgrade your SQL server version to SQL 2008 SP1 cumulative update package 6 (prerequisite). Not sure if you're still running this CU.
    Hope this will help.
    Best Regards,
    Patrick

  • Unable to cast object of type 'Microsoft.Xrm.Sdk.Entity' to type

    when I using below code :
     using (ServiceContext svcContext = new ServiceContext(service))
                    var creditNote = svcContext.new_credit_noteSet.Where(c => c.new_credit_noteId == cnid).FirstOrDefault();
    got this error:
    System.InvalidCastException: Unable to cast object of type 'Microsoft.Xrm.Sdk.Entity' to type 'TCT.CRM.Model.new_credit_note'.
       at System.Linq.Enumerable.&lt;CastIterator&gt;d__b1`1.MoveNext()
       at Microsoft.Xrm.Sdk.Linq.PagedItemCollection`1.MoveNext()
       at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
       at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
       at HP.Crm2013.Plugins.ServiceManage.sm_credit_note_update_post.CalculateTotalAmount(IOrganizationService service, Guid cnid)
       at HP.Crm2013.Plugins.ServiceManage.sm_credit_note_update_post.Execute(IServiceProvider serviceProvider)
    any help?
    Awen

    Hi Awen,
    This kind of error usualy occur if we dont have enable proxytype for the CRM service.
    Add the below line in your code after creating the service proxy and check :
    _serviceProxy.EnableProxyTypes();
    Thanks,
    Seban

Maybe you are looking for

  • 'Tricking' the App Store to allow re-downloading a purchase

    Hopefully short version of a rather long ordeal: An app I use recently became available only on the MAS. After paying and downloading it, I discovered that the old version was still installed as a Pref Pane. The developer's site suggested using an un

  • My itunes suddenly crashes and I need to reinstall it.  Iam using a windows 7 64 bit

    I am using an Asus K43S notebook with a Windows 7 Home basic OS 64 bit. I have been having problems with my itunes and this problem is a persistent one.  How can this be remedied. 

  • Subject line of email question

    In a script the following is saving a file as Email Date then the date then the time. Instead of having the "name" Email Date I would like the subject of the email there. What is the command to put the subject line there? keystroke "Email Date " & sh

  • None of the functions in the sample editor are appearing

    Every time i go to the sample editor the editing functions are all greyed out, with the exception of gain I am using some of the logic content Is there an easy way around this? Did I not correctly install the au stuff?

  • 'FOR' cursor problem

    Hello, I'm trying to write a cursor like: begin     if param_number is null then       open c_cer;       fetch c_cer into r_cer;       close c_cer;     end if;    for r in c(nvl(param_number,r_cer.id)) loop      <something>     end loop; end;I got OR