Reputation: 6882
In my cache class, I'm going to have a function which writes the serialized version of an object (undecided type) to a file, something like this (generic function):
public <O> void write(O object) {
// ...
serialize(file, object);
// ...
}
Which works great, however, I'm unable to find a way to create a method which can return any object, like the write()
method can take any object. Looking for something like this:
public <O> read() {
// ...
O object = unserialize(file);
// ...
return object;
}
Any suggestions on how to accomplish this is highly appreciated!
Upvotes: 0
Views: 8025
Reputation: 31303
Yes,
public <O> O read()
is valid and will do what you want (return any type the caller wants). Whether this is a good idea is another matter
Upvotes: 0
Reputation: 30723
I'm assuming the caller to read() knows which type it expects to get. This is a reasonable assumption because he is going to assign the return value to some variable:
MyType o = read(...); // Caller knows he's going to get a MyType object
If this assumption is true, then you should change the read()
method such that it takes a class object:
public<T> T read(Class<T> t) {
...
}
Then the call site will look as follows:
MyType o = read(MyType.class);
Upvotes: 0
Reputation: 7863
I would do that by making the whole class generic
class Cache <O extends Serializable> {
public void write(O object) {
serialize(file, object);
}
public O read() {
O object = (O)unserialize(file);
return object;
}
}
Note the cast of the returned object.
Besides that you should use <O extends Serializable>
instead of just <O>
. This assures that your type parameter id a type that is serializable. This is needed if you want to save (serialize) objects and prevents later errors.
Upvotes: 0
Reputation: 82899
Not sure if I understood the question correctly... You could wrap both methods inside a class and parametrize the class with the object's type, like this:
public class ReaderWriter <T> {
public ReaderWriter(File file) {...}
public void write(T object) {...}
public T read() {...}
}
Upvotes: 0
Reputation: 533492
If you mean
public <O> O read() {
this is almost useless because it is much the same as
public Object read() {
Upvotes: 1
Reputation: 174957
You specify the return type of type Object:
public Object function(...)
That way the return type will always be of type Object (since all objects are descendants of Object
), so they will be accepted.
Upvotes: 7