Solved

How do I cast variable types in Java?

Posted on 1998-07-31
7
193 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 

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 Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
arguments to jar 5 26
Java exception bubble up 2 18
eclipse buid path vs tomcat lib path 10 23
difference between sorce folder and folder in eclipise 3 13
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
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 different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

777 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