I have two classes Foo1
and Foo2
very similar fields.
And I have a convert method that accepts Foo1
class as shown below
public static <T> T convert(IFoo1 foo1, Class<T extends IFoo2> clz) {
T foo2 = clz.newInstance();
// Setter methods
return foo2;
}
But I'm getting error : Syntax error on token "extends", , expected
Both the classes Foo1
and Foo2
implements interface IFoo1
and IFoo2
.
The error you are getting is because your generic is using improper bounding.
Change your method declaration to:
public static <T extends IFoo2> T convert(IFoo1 foo1, Class<T> clz) {
T foo2 = clz.newInstance();
....
return foo2;
}
There is another type of bounding you may have been thinking of. I recommend reading this SO question: Understanding upper and lower bounds on ? in Java Generics