简体   繁体   中英

Java - Passing a class to a function

I'm implementing serialization, and am trying to make everything as modular as possible. When reading objects from files, I'm trying to use just one function to pass everything to an ArrayList, or something of that sort. Currently I'm doing something like this:

public static ArrayList<Class1> ReadClass1(String fileName) {
    ArrayList p = null;
    try {
        ObjectInputStream in = new ObjectInputStream(
                new BufferedInputStream(
                        new FileInputStream(fileName)));
        p = new ArrayList<Class1>();
        while (1 != 2) {
            p.add((Class1) in.readObject());
        }
    } catch (Exception e) {
        ;
    }
    
    return p;

}

However, I want to read other classes, let's say Class2 or Class3 , and right now I'm copy-pasting the code and just editing everything that says "Class1" to "Class2". Is there a way to pass in a specific type I want to use, like this?

public static ArrayList<myClass> ReadProducts(String fileName, myClass) { //where myClass is a class
    ArrayList p = null;
    try {
        ObjectInputStream in = new ObjectInputStream(
                new BufferedInputStream(
                        new FileInputStream(fileName)));
        p = new ArrayList<myClass>();
        while (1 != 2) {
            p.add((myClass) in.readObject());
        }
    } catch (Exception e) {
        ;
    }
    
    return p;

}

So that I could reuse the function for different classes?

You can use java Generics . Please find the code below:

public static <T> ArrayList<T> ReadProducts(String fileName, Class<T> t) {
        ArrayList p = null;
        try {
            ObjectInputStream in = new ObjectInputStream(
                    new BufferedInputStream(
                            new FileInputStream(fileName)));
            p = new ArrayList<T>();

            while (1 != 2) {
                p.add(t.cast(in.readObject()));
            }
        } catch (Exception e) {
            ;
        }
        return p;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM