如何自定义泛型类型?

时间:2017-10-14 00:48:04

标签: java generics interface

我有这样的界面:

public class CustomizedBeanCreator<T> implements BeanCreator<T>{

    @Override
    public T createBean() {
        CustomizedBean bean = new CustomizedBean();
        bean.setId(-2323);
        bean.setName("this bean is created by a customized creator");       
        @SuppressWarnings("unchecked")
        T t = (T)bean;      
        return t;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Class<T> getClazz() {
        return (Class<T>) CustomizedBean.class;
    }
}

我试着定制它:

Creating Auto Scaling group named: [xxx] failed. Reason: You have requested more instances (1) than your current instance limit of 0 allows for the specified instance type. Please visit http://aws.amazon.com/contact-us/ec2-request to request an adjustment to this limit. Launching EC2 instance failed.

由于这两个@SuppressWarnings,我感到很不舒服。

我该怎么办才能修复它?

谢谢!

3 个答案:

答案 0 :(得分:5)

更改签名(和实施)
public class CustomizedBeanCreator<T> implements BeanCreator<T>{

类似

public static class CustomizedBeanCreator implements BeanCreator<CustomizedBean> {

    @Override
    public CustomizedBean createBean() {
        CustomizedBean bean = new CustomizedBean();
        bean.setId(-2323);
        bean.setName("this bean is created by a customized creator");
        return bean;
    }

    @Override
    public Class<CustomizedBean> getClazz() {
        return CustomizedBean.class;
    }
}

答案 1 :(得分:2)

public class CustomizedBeanCreator implements BeanCreator<CustomizedBean> {
    @Override
    public CustomizedBean createBean() {
        CustomizedBean bean = new CustomizedBean();
        bean.setId(-2323);
        bean.setName("this bean is created by a customized creator");       
        return bean;
    }

    @Override
    public Class<CustomizedBean> getClazz() {
        return CustomizedBean.class;
    }
}

答案 2 :(得分:2)

正如Elliott Frisch所述,您需要实施BeanCreator<CustomizedBean>而非BeanCreator<T>,原因如下:

@Override
public T createBean() {
    CustomizedBean bean = new CustomizedBean();
    bean.setId(-2323);
    bean.setName("this bean is created by a customized creator");       
    @SuppressWarnings("unchecked")
    T t = (T)bean;      
    return t;
}

在这段代码中你说你可以返回类型T,但是你从不说T是CustomizedBean,所以编译器不能确定bean是T类型的,所以这种情况不安全

例如,您可以请求CustomizedBeanCreator<String>的实例,并且编译器会期望createBean()返回一个String,并且尝试将CustomizedBean转换为String会导致ClassCastException。 / p>