我想创建一个 GenericBuilder,它可用于检索在我的类中定义的 Builder 类。我创建了以下接口和类
public interface BuilderType<T> {
}
public class MyObject implements BuilderType<MyObject.MyObjectBuilder> {
private int i;
private MyObject() {}
public int getI() {
return i;
}
public static MyObjectBuilder buildMyObject() {
MyObjectBuilder builder = new MyObjectBuilder();
return builder;
}
public static class MyObjectBuilder {
private final MyObject obj;
MyObjectBuilder() {
obj = new MyObject();
}
public MyObjectBuilder withI(int i) {
obj.i = i;
return this;
}
public MyObject build() {
return obj;
}
}
public class GenericBuilder {
public static <T extends BuilderType<S>, S> S getBuilder(Class<T> t) {
S s = null;
try {
s = (S) t.getDeclaredMethod("build" + t.getSimpleName(), null)
.invoke(null, null);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
}
我的 GenericBuilder 中的语句 s=(S)t.get... 给出了强制转换警告: Unchecked Cast from Object to S,有没有办法消除它?