使用泛型将一个对象转换为另一个对象
Convert one object to another using generics
我有两个 class Foo1
和 Foo2
非常相似的字段。
我有一个接受 Foo1
class 的转换方法,如下所示
public static <T> T convert(IFoo1 foo1, Class<T extends IFoo2> clz) {
T foo2 = clz.newInstance();
// Setter methods
return foo2;
}
但我收到错误:令牌语法错误 "extends",预期
classes Foo1
和 Foo2
都实现了接口 IFoo1
和 IFoo2
。
您收到的错误是因为您的泛型使用了不正确的边界。
将您的方法声明更改为:
public static <T extends IFoo2> T convert(IFoo1 foo1, Class<T> clz) {
T foo2 = clz.newInstance();
....
return foo2;
}
您可能一直在考虑另一种类型的边界。我建议阅读这个 SO 问题:Understanding upper and lower bounds on ? in Java Generics
我有两个 class Foo1
和 Foo2
非常相似的字段。
我有一个接受 Foo1
class 的转换方法,如下所示
public static <T> T convert(IFoo1 foo1, Class<T extends IFoo2> clz) {
T foo2 = clz.newInstance();
// Setter methods
return foo2;
}
但我收到错误:令牌语法错误 "extends",预期
classes Foo1
和 Foo2
都实现了接口 IFoo1
和 IFoo2
。
您收到的错误是因为您的泛型使用了不正确的边界。
将您的方法声明更改为:
public static <T extends IFoo2> T convert(IFoo1 foo1, Class<T> clz) {
T foo2 = clz.newInstance();
....
return foo2;
}
您可能一直在考虑另一种类型的边界。我建议阅读这个 SO 问题:Understanding upper and lower bounds on ? in Java Generics