[英]Java Generics get the Type from the method (that creates object) using reflection
I wanted to create a GenericBuilder that could be used to retrieve the Builder classes that are defined inside my classes. 我想创建一个GenericBuilder,该类可用于检索在类内部定义的Builder类。 I created the following interfaces and classes
我创建了以下接口和类
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;
}
}
the statement s=(S)t.get... in my GenericBuilder gives a cast warning: Unchecked Cast from Object to S, is there a way to eliminate it?? 我的GenericBuilder中的语句s =(S)t.get ...给出了强制转换警告:取消选中从Object到S的强制转换,有没有办法消除它?
There is no way to eliminate the warning because S
is not a real type. 由于
S
不是实数,因此无法消除该警告。 By runtime it will get erased to its upper bound, which is Object
in your case. 在运行时,它将被擦除到上限,在您的情况下为
Object
。 So the "downcast" isn't actually doing anything. 因此,“垂头丧气”实际上没有做任何事情。 You can check the
Method
's return type by calling the appropriate method, and then do a reflective downcast (not very helpful for your scenario). 您可以通过调用适当的方法来检查
Method
的返回类型,然后进行反射式向下转换(对您的情况不是很有用)。 Type safety cannot possibly be achieved when you dynamically fetch a method at runtime. 在运行时动态获取方法时,可能无法实现类型安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.