How can Java dynamically pass in the generic type T?

In Java, it is not possible to directly pass in generic parameter T dynamically. T is determined at compile time and cannot be passed dynamically at runtime.

However, a similar effect can be achieved by defining generic parameters in methods or classes. For example:

public class MyGenericClass<T> {
    private T value;

    public void setValue(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        MyGenericClass<String> myString = new MyGenericClass<>();
        myString.setValue("Hello");
        System.out.println(myString.getValue()); // 输出: Hello

        MyGenericClass<Integer> myInteger = new MyGenericClass<>();
        myInteger.setValue(123);
        System.out.println(myInteger.getValue()); // 输出: 123
    }
}

In the example above, by defining a generic parameter T in the MyGenericClass class, different types can be dynamically passed in while maintaining type safety.

bannerAds