Solved

How do I cast variable types in Java?

Posted on 1998-07-31
7
201 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

 

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

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

726 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