Generic Casting

Is there a way to pass an object to return the general value of a method? I tried this way, but it happened. Cast exception:

public <S extends Super> S get(Class<S> clazz) {
    return (S) new Super();
}

public class Super {

}

public class Sub1 extends Super {

}

public class Sub2 extends Super {

}

An exception:

java.lang.ClassCastException: 
Cannot cast com.zarinak.app.model.Super to com.zarinak.app.model.Sub1

is there any way?

+4
source share
1 answer

The way you are trying to apply a new Super object to the type of object that extended it is incorrect.

, Sub1. Super Super, , Sub1, ; Sub1 Sub1. , Sub1 . , , Sub1 , Super . , .

, . S- Super, Super- .

public <S extends Super> S get(Class<S> clazz) throws IllegalAccessException, InstantiationException {
    S s = clazz.newInstance();
    return s;
}

, - , , clazz.newInstance(). , , Super.

+5

Source: https://habr.com/ru/post/1691479/


All Articles