h*********o 发帖数: 62 | 1 public class Base {
private Class persistentClass;
public Base() {
Class clazz = getClass();
this.persistentClass = (Class) ((ParameterizedType)
clazz.getGenericSuperclass()).getActualTypeArguments()[0];
}
}
It seems that there is no way you can use it as follows:
Base b = new Base();
to use it you have to define a subclass specifying the type parameter just
as you do in C++ template.
BaseDerative extends Base....
NOT: |
m******t 发帖数: 2416 | 2 Interesting... note though that the "String" you get is not the "String"
from "BaseDeritive", but the one from "Base".
In other words, it'll work even with "BaseDeritive extends Base". |
h*********o 发帖数: 62 | 3 rite.
That is exactly how Hibernate does.
Do not know under hood how jvm handles this thing. |
F****n 发帖数: 3271 | 4 It's not a JVM implementation issue. It's simply the way Generics should be.
Remeber Java Generics is a compile time thing rather than runtime thing. In
other words, if you declare Base, then the parameter of this class is a
TypeVariable.
Even if you define a new Base variable, its type parameter is still
a TypeVariable because Base only help you check type at compile type
. It will not changed the parameter of Base into a String.
Consequently, your original code will throw
【在 h*********o 的大作中提到】 : public class Base { : private Class persistentClass; : : public Base() { : Class clazz = getClass(); : this.persistentClass = (Class) ((ParameterizedType) : clazz.getGenericSuperclass()).getActualTypeArguments()[0]; : : } : }
|