I have function
private Class readObject (ObjectInput in, Class objectclass){
try {
Object o = in.readObject ();
if (o instanceof objectclass) {
return (objectclass)o;
}
} catch (Exception e) {
}
In my class I am calling this function with:
ObjectInput in = (..)
Type1 type = readObject (in, Type1.class);
(do something with type)
while(true){
Type2 type2 = readObject (in, Type2.class);
(do something with type2)
Basically, readObject is supposed to return the class that I have as a parameter, if that is the correct type of Object o. You can think of this as, I have Type1, Type2 and Type3 objects that I am reading, but if I come across Type3 I do nothing.
This code that I have written does not work properly. For example,
Type1 type = readObject (in, Type1.class);
gives me the warning "cannot convert from Class to Type1".
The getReturnType() method of Method classEvery Method has a return type whether it is void, int, double, string or any other datatype. The getReturnType() method of Method class returns a Class object that represent the return type, declared in method at time of creating the method.
When a method uses a class name as its return type, such as pop does, the class of the type of the returned object must be either a subclass of or the exact class of the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.
clone() method or define a constructor that takes an object of its class as a parameter.
A class that requires the user id, will simply require the GUID userId as a parameter, sometimes we might need the username as well, so that is passed in as a separate parameter. In some cases, this is passed to individual methods, so the values are not held at the class level at all.
You should make your method generic and return an instance of T
(instead of an instance of Class<T>
):
private <T> T readObject (ObjectInput in, Class<T> objectclass)
EDIT: You should also change your if
and your cast, as follows:
if (objectclass.isInstance(o)) {
return (T) o;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With