Programmatically setting a list identifier

Niaz Ahsan :

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

Mohamed Anees A :

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

  • It kills the idea of generics.
  • Makes your code prone to ClassCastException.
  • In a perfect world and even if you are safe while adding elements, you will need to suppress warning everywhere and need to cast back to the type.

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));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77206&siteId=1