Redian新闻
>
An interesting thing about java generics-do not laugh at me if u think it too basic
avatar
An interesting thing about java generics-do not laugh at me if u think it too basic# Java - 爪哇娇娃
w*d
1
我常重复做梦自己在一栋老家的房子里狂跑,后面一直有人在追我,具体谁不知道,梦
里觉得很害怕,我就一直跑,告诉自己只要离开这个屋子就安全了,可是跑到天亮也没
有跑出去,这能说明什么吗?这个梦重复作了好几年,这里能给解释解释吗?
avatar
h*o
2
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:
avatar
i*n
3
你的前世在那个屋子里练长跑来着。
avatar
m*t
4
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".
avatar
w*d
5
假半仙。。。。。

【在 i*******n 的大作中提到】
: 你的前世在那个屋子里练长跑来着。
avatar
h*o
6
rite.
That is exactly how Hibernate does.
Do not know under hood how jvm handles this thing.
avatar
i*n
7
嘿嘿,被你看出来了。
不过说到梦,我想起了原来看过的一部小说,好像名字叫“梦境”,倪匡写的,比较诡
异。

【在 w********d 的大作中提到】
: 假半仙。。。。。
avatar
F*n
8
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];
:
: }
: }

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。