Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Dynamic Casting Object to List<?>

Tags:

java

I have a situation to where I need to cast Object to List<SomeClassName>.

I get the object value List<SomeClass> from request parameter.

I need to cast this Object into List<SomeClass>. I don't know the SomeClass at compile time.

I can get the class type at run time as String.

Sample:

private static Object createList(Object object){

      List dd = (List)object;

      //the List contains the objects of this class
      Class cls = Class.forName(dd.get(0).getClass().getName());

      //I would like to cast this Object to List<thisClass>
}

for example the class is jp.Dto.UserDto then the casting should be like List<jp.dto.UserDto> list = (List<jp.dto.UserDto>)Object; but the problem here is I don't know jp.dto.UserDto class at compile time. I can get this at run time only.

How this can be achieved?

like image 848
Jaypee Avatar asked Feb 22 '12 10:02

Jaypee


2 Answers

Basically, which I not really recommend, you can do something like this, the type restriction is not even necessary:

 public static void main(String[] args) {
    Object list = new ArrayList<String>();
    List<Integer> integers = cast(list);
}


@SuppressWarnings("unchecked")
public static <T extends List<?>> T cast(Object obj) {
    return (T) obj;
}

It also shows the problem it introduces

like image 194
M Platvoet Avatar answered Nov 01 '22 16:11

M Platvoet


You should understand that Generics in Java i.e. the stuff between <> is erased at runtime, so declaring a list like the following is perfectly legal.

List list = (List)someObject;

furthermore adding objects to this list like the following is also permitted

list.add(someObjectOfACertainClass);

From what I understand you are being passed an object which is a list of objects of a certain class and you want to iterate through that list in a compile time type safe manner. You can do something like the following:

private static <T> Object createList(List<T> argumentList) {
    List<T> otherList = new ArrayList<T>();
    //do something here
    return otherList;
}
like image 25
Puneet Avatar answered Nov 01 '22 17:11

Puneet