Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return class type and have class type as parameter

Tags:

java

class

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

like image 402
hokosha Avatar asked May 30 '16 13:05

hokosha


People also ask

Can we have class as return type in Java?

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.

Can a class be a return type?

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.

Which method returns class type of the argument passed as parameter?

clone() method or define a constructor that takes an object of its class as a parameter.

Can we pass 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.


1 Answers

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;
}
like image 174
fps Avatar answered Oct 03 '22 07:10

fps