简体   繁体   中英

Return object from passed class parameter

In my program I have an abstract class A and some other classes which extends from A. Here is a little excerpt from my code:

public abstract class A {
    public A(int[] values) {
        // ...
    }
}

public class B extends A {
    public B(int[] values) {
        super(values);
        // setup other things
    }
}

// some more classes like B

Now I have a class which reads out some integer values from a file and writes them in an array. This class only have static methods and I want to return an object from a passed class. With this code I can give the class B to the method but how can I create and return an object of the class with I have called the method? I tried wi this:

B obj = Reader.readFromFile(path, B.class);

public class Reader {
    public static *** readFromFile(String path, Class<? extends A> c) {
        // read out the file and store values in an array
        // how can I create an object of the parameter c and return it from here?
    }
}

I do not want to make the whole class generic. Any ideas how to do this or is this not possible in Java?

You can create instance of provided class via reflection. In your case you need to get a proper constructor via c.getConstructor(int[].class) and then create new object calling newInstance(...) method of that constructor

Another solution would be that you instantiate the object before calling the method, and pass that instance to the method. Then, you could use a setter to pass the values:

public static void readFromFile(String path, A c) {
    c.setValues(...);
}

B should then provide a nullary constructor.

If you really need to instantiate the object within the method, you could still use reflection :

public static void readFromFile(String path, Class<? extends A> c) {
    int[] values = ...;
    Constructor<T> constructor = c.getConstructor(int[].class);
    T instance = constructor.newInstance(values);
}

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