Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How do I cast variable types in Java?

Posted on 1998-07-31
7
Medium Priority
?
209 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 200 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 does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
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…
Suggested Courses

618 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