Reputation: 7117
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?
Upvotes: 0
Views: 84
Reputation: 48817
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);
}
Upvotes: 1
Reputation: 4683
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
Upvotes: 3