Let's say I have a method with a generic parameter:
public <U> void genericMethod(U param) {
// doStuff
}
I also have two classes, one of which extends the other:
public class A {}
public class B extends A {}
And I do this:
A var = new B();
genericMethod(var);
In genericMethod
, what is the type of U
?
The variable I passed genericMethod
is declared as A
, but is actually B
, so is U
of type A
or B
?
I've tried testing it but I can't find a way to get information on U
at runtime.
Let's modify your example a little:
public class Example {
static class A {
int x;
}
static class B extends A {}
static <U> U genericMethod(U param) {
int i = param.x; // compile time error
System.out.println(param.getClass()); // prints B
return param;
}
public static void main(String... args) {
A var1 = new B();
A var2 = genericMethod(var1);
B var3 = genericMethod(var1); // compile time error
}
}
From the point of view of your invocation of genericMethod
, U is of type A, so we can assign the return value to A, but not to B.
From the point of view of the implementation of genericMethod
, U is of type Object
, because we haven't put any bounds on it, so we can't, for instance, refer to a member field of A. If we wrote static <U extends A> U genericMethod(U param)
then the type of U would be A.
The actual runtime type of param
is B, as you can see if you call getClass()
Generic types are resolved in compiler time. Therefore, <U>
is determined by the compile-time type of var
, which is A
.
U
is of type Object
, because you can pass anything to genericMethod.
It could be a String, an Integer, an A or a B or anything else. The most common denominator of all objects is Object
, so inside genericMethod the type of param will be Object.
If you need U
to be an A or B, it could be defined as
public <U extends A> void genericMethod(U param) {
But again the only guarantee is it is (at least) an A and so you can access properties and methods of A, but not B (though B can override properties of A).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.