A java class contains an instance variable which is a List
.
I need to set the type of object that this List
holds in a String
variable.
private List<VARIABLE> myList;
String VARIABLE = "BasicDegreeClass";
Is this allowed to do in JAVA If so, how can this be achieved?
Thanks in advance
First, you will have to create a List where T is the Type of objects contained in the list.
So, your code should read as
private List<T> myList;
From the javadoc,
<T> the type of elements in this list.
In your case, the compiler will not know the type of elements that is to be added to your list and hence it won't work.
However you can use List<Object>
as an alternate, but that is a generally code-smell in long run and very difficult to maintain
Proper Solution : You can write an interface, which all your objects of the ArrayList will adhere to. Proceed with something like
List<'YOUR INTERFACE TYPE HERE'> myList = new ArrayList<>();
Don't you need to worry of the object type inside the list. Hope this helps!
If you are too specific to save in String, here is a workaround.
public static <T> List<T> getCastedList(List<Object> objList, Class<T> clazz) {
List<T> newList = new ArrayList<T>();
if (objList != null) {
for (Object object : objList) {
if (object != null && clazz.isAssignableFrom(object.getClass())) {
newList.add((T) object);
}
}
}
return newList;
}
And call this as
getCastedList(myList, Class.forName(VARIABLE));