Reputation: 26428
I have a java.io.Reader as the return type of my method. But i have Object type of an instance which i get from Database. So how can I convert this to Reader type and return?
I have the following code where getByteArrayObject() return a byte array. and the same i need to return, but the return type is Reader which i cant change.
public Reader getMediaReader(String arg0) {
// TODO Auto-generated method stub
Object obj = getByteArrayObject();
System.out.println("HELLO I AM DETCTED....... in getMediaReader");
return null;
}
need help thanks.
Upvotes: 0
Views: 429
Reputation: 719576
Based on your edited question ...
Assuming that the byte array returned by getByteArrayObject()
is text encoded in some known character set / encoding, then the following should suffice:
public Reader getMediaReader(String arg0) throws IOException {
byte[] bytes = getByteArrayObject();
return new InputStreamReader(
new ByteArrayInputStream(bytes), ENCODING_NAME);
}
where ENCODING_NAME
is the name of the encoding.
EDIT - I'd hazard a guess that the arg0
parameter is supposed to contain the encoding name.
Upvotes: 3
Reputation: 1503479
Well how does the caller expect to read the data? What are they expecting to get?
It sounds like you might want to serialize to some sort of text-based format (JSON? XML?) and then return a StringReader
which will let the client read that data. But it really depends on what the client is expecting... and you may well need to write a similar method to create a new instance of your object based on that text data.
It's worth considering versioning when you think about serialization too - once you've got the basics of what you want to do, think about what should happen if you ever add a field to your class. How will you read old data? What would the old code do with your new data? How backward and forward compatible do you need to be?
Upvotes: 2
Reputation: 3051
First I would like to clarify that there is not concept in java to convert one object into another automatically. What kind of Object are u getting from DB? Is it itself a serialized version of reader object, then on deserialization you should get back reader object. If you want to construct a reader object from content in the object, assuming there is a string data you want to read, you need to create a StringReader and return that back as that extends reader.
Reader class in Java represent character stream hierarchy.
Upvotes: 1