Java - Generics vs Casting Objects

前端 未结 4 1153
野的像风
野的像风 2021-01-03 10:32

I have a class Data

with a generic attribute

private T value;

is there nicer way to do the following?
ie

4条回答
  •  自闭症患者
    2021-01-03 11:11

    You could ask if "value" is assignable to the expected class.

    private T value;
    .
    .
    .
    public Object getValueAsObjectOfClass(Class expectedClass) {
        if(!expectedClass.isAssignableFrom(value.getClass())) {
            // abort gracefully
        }
        return expectedClass.cast(value);
    }
    

提交回复
热议问题