hokosha
hokosha

Reputation: 313

Return class type and have class type as parameter

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".

Upvotes: 8

Views: 14492

Answers (2)

fps
fps

Reputation: 34470

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;
}

Upvotes: 14

Nicolas Filotto
Nicolas Filotto

Reputation: 45005

You have 2 things to do:

  1. Change the signature of your method as next:

    private <T> T readObject (ObjectInput in, Class<T> objectclass) {

  2. Cast your object dynamically using Class.cast as next:

    return objectclass.cast(o);

Upvotes: 5

Related Questions