Solved

How do I cast variable types in Java?

Posted on 1998-07-31
7
190 Views
Last Modified: 2012-05-04
Hi guys!, I have a class with only variables, and I need to read from a Socket with the class DataInputStream into my class, I don't want to copy var per var, is there any way to cast from a byte[] to class type some bytes?
That is:
class myType{
  short Op;
  short ID;
  int     hWnd;
  int    Time;
 }

[..]
DataInputStream Data;
myType t;

Data.read(t,  0,sizeof(t));  <-------- How can I do this? read info into my data type, just cast?,

Thank you!
0
Comment
Question by:trickle
  • 4
  • 2
7 Comments
 
LVL 2

Expert Comment

by:shchuka
ID: 1229419
I don't think you can do it directly in Java.  One thing to try is to use DataOutputStream to write a bunch of bytes to a disk file and then ObjectInputStream to read an object (with casting, of course)
0
 
LVL 3

Accepted Solution

by:
mjenkins earned 100 total points
ID: 1229420
Why not just try this:

import java.io.*;
 
public class Foo
    implements Serializable
{
    public static void main( String args[] )
    {
        Foo foo = new Foo( (short)1, (short)2, 3, 4 );
        Foo foo2;
 
        try
        {
            System.out.println( "Starting" );
            FileOutputStream ostream = new FileOutputStream("t.tmp");
            ObjectOutputStream p = new ObjectOutputStream(ostream);
            p.writeObject(foo);
            p.flush();
            ostream.close();
            System.out.println( "Reading" );
            FileInputStream istream = new FileInputStream("t.tmp");
            ObjectInputStream p2 = new ObjectInputStream(istream);
            foo2 = (Foo)p2.readObject();
            istream.close();
 
            System.out.println( "Op = " + foo2.Op );
            System.out.println( "Id = " + foo2.ID );
            System.out.println( "hWnd = " + foo2.hWnd );
            System.out.println( "Time = " + foo2.Time );
        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
 
        System.out.println( "Done" );
    }
 
    public Foo( short a, short b, int c, int d )
    {
        Op = a;
        ID = b;
        hWnd = c;
        Time = d;
    }
 
    short Op;
    short ID;
    int     hWnd;
    int    Time;
}

That makes the whole process transparent to you.
0
 

Expert Comment

by:tomd012698
ID: 1229421
 I am pretty sure that your code example will get you trouble.  There is more to a class than just the raw data that makes it up.  While you might get away with it, simply casting a chunk of raw data into a class is not a secure solution.  You should not  assumine knowledge of the physical structure of the class in memory.  This would amount to a security issue with Java, and most likely be disallowed.

  An easy solution would be to create a constructor for your class that takes an array of bytes, and an index within that array to pull from.  Then you could copy all of the bytes out of the stream, and use the constructors to build classes that you place into a second array.  The only disadvantage is that you would have to keep the data array until you are done converting, unless you wanted to use a threaded strategy.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Expert Comment

by:tomd012698
ID: 1229422
By the way..... My comment was to the original question, not to the answer by mjenkins.
0
 
LVL 3

Expert Comment

by:mjenkins
ID: 1229423
tomd is absolutely correct in stating that simply reading and writting the byte stream in this case is undesirable. The behavior is undefined. My solution simply amounts to identifying your class as "Serializable" in order to allow the default readObject() and writeObject() methods to work. Of course, the main() method is just there to demostrate the solution.
0
 
LVL 3

Expert Comment

by:mjenkins
ID: 1229424
tomd is absolutely correct in stating that simply reading and writting the byte stream in this case is undesirable. The behavior is undefined. My solution simply amounts to identifying your class as "Serializable" in order to allow the default readObject() and writeObject() methods to work. Of course, the main() method is just there to demostrate the solution.
0
 
LVL 3

Expert Comment

by:mjenkins
ID: 1229425
Did this answer your question? You haven't replied in two weeks. I would appreciate a grade for the answer I suplied  :)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now