Good day.
There was a task:
at the Object input, however I know (checked earlier: o.getClass (). isArray ()) that it can contain an array of any type, either primitive or not (int [], Object [], SomeClass [], and t .d.)
At first I solved the problem without escaping the raw type:
static List getListRaw(Class clazz, Object o){ if (clazz==int[].class){ return IntStream.of((int[]) o).boxed().collect(Collectors.toList()); } else { return Stream.of((Object[])o).collect(Collectors.toList()); } } Casting, creating arrays of the remaining 7 primitives and checking for an array are omitted.
However, it is clear that this method is bad:
Object intArray = new int[]{1, 2, 3}; List<String> rawArray = getListRaw(intArray.getClass(), intArray); rawArray.add("oops"); rawArray.forEach(System.out::println); A typical mistake is the misuse of generics.
I wanted to make a generalized method with about this signature:
<T> List<T> getList(Class<T> clazz, Object o) And then there were problems, I do not know how to do it.
If I write something like this:
static <T> List<T> getList(Class<T> clazz, Object o){ if (clazz==int[].class){ //не компилируется //return IntStream.of((int[]) o).boxed().collect(Collectors.toList()); return (List<T>) Arrays.asList((int[]) o); } else { //return (List<T>) Stream.of((Object[])o).collect(Collectors.toList()); return (List<T>) Arrays.asList((Object[])o); } } Then the following problems:
1) If the type is not primitive (getList (nonPrimitive.getClass (), nonPrimitive);), then a list of objects that need to be manually cast is returned, which we would like to avoid (if you submit ClassName.class instead of nonPrimitive.getClass (), then everything works , but I don't have a ClassName in general)
2) If the type is primitive, the method described above returns a List of one element in which the array is placed, and this List is also Object. The method via IntStream does not work as it returns a specific sheet int, which is not assigned to List <T>
In principle, for my problem raw type is not terrible, but purely academic interest - how to solve the problem as correctly as possible?
I specify (do not touch the primitives - this is a special case):
Object pojoArray = new Pojo[]{new Pojo(1), new Pojo(2)}; getList(pojoArray.getClass(), pojoArray).forEach(o -> { //o надо кастить но я не знаю на что }); getList(Pojo.class, pojoArray).forEach(o -> { //o не надо кастить но у меня нет информации о Pojo.class });
oinforEach? I mean, if you can write(Pojo)oin lambda body, then you can passPojo.classtogetList. - zRrr