gpt4 book ai didi

java - 如何自定义泛型?

转载 作者:行者123 更新时间:2023-11-29 09:59:13 25 4
gpt4 key购买 nike

我有一个这样的界面:

public interface BeanCreator<T> {   
public T createBean();
public Class<T> getClazz();
}

我试着定制它:

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;
}
}

因为那两个@SuppressWarnings,我感到不舒服。

我应该怎么做才能修复它?

谢谢!

最佳答案

更改签名(和实现)来自

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;
}
}

关于java - 如何自定义泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46739734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com