Skip to content
Advertisement

How to pass an object type to constructor as argument and cast a variable to it (JAVA)?

I have a class that accepts a ArrayList<?> as a constructor argument:

public class Test {

    public Test (ArrayList<?> data) {

    }
}

I want to cast data to ArrayList<Type>, and pass Type to constructor as an argument, something like this :

public class Test {

    public Test (ArrayList<?> data, Class type) {
        ArrayList<Type> newData = (ArrayList<type>) data;
    }
}

How can i do this in Java?

Advertisement

Answer

You have to use a generic parameter, to get the class pointed by the Class instance

public <T> Test(ArrayList<?> data, Class<T> type) {
    ArrayList<T> newData = (ArrayList<T>) data;
}

But this is not safe as you just assume every object fits the class, you’d better cast every object one by one

public <T> Test(ArrayList<?> data, Class<T> type) {
    ArrayList<T> newData = data.stream().map(o -> (T) o).collect(Collectors.toCollection(ArrayList::new));
}

Multiple classes

public <T, U> Test(ArrayList<?> data1, Class<T> type1, ArrayList<?> data2, Class<U> type2) {
    ArrayList<T> newData1 = data1.stream().map(o -> (T) o).collect(Collectors.toCollection(ArrayList::new));
    ArrayList<U> newData2 = data2.stream().map(o -> (U) o).collect(Collectors.toCollection(ArrayList::new));
}

Instanciate an object from a Class<T> type

T item = type.getDeclaredConstructor().newInstance();
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement