I am trying to make the following method to a generic method and got struck.
public static MyObject[] getObjectFromList(List<MyObject> inputList) {
if (inputList != null && inputList.size() > 0) {
return inputList.toArray(new MyObject[inputList.size()]);
} else {
inputList = new ArrayList<MyObject>();
MyObject obj = new MyObject();
inputList.add(obj);
return inputList.toArray(new MyObject[inputList.size()]);
}
}
and have the other method which is similar but it’s MyObject2
public static MyObject2[] getObjectFromList(List<MyObject2> inputList) {
if (inputList != null && inputList.size() > 0) {
return inputList.toArray(new MyObject2[inputList.size()]);
} else {
inputList = new ArrayList<MyObject2>();
MyObject2 obj = new MyObject2();
inputList.add(obj);
return inputList.toArray(new MyObject2[inputList.size()]);
}
}
How do I make this as a single method which takes any object(myobject,myobject2) list and
returns an array ?
You can’t do it without changing method signature due to type erasure. If you can pass a
Classobject identifying the desired type you can do something like this: