Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

关于 Type接口和ParameterizedType接口之间强转的疑问~!

看一个GenricDaoImpl代码时候存在一个疑问:

Java code?

1

2

3

4

5

6

7

8

9

10

public?class?GenricDaoImpl<T?`extends?Serializable,?PK?`extends?Serializable>

implements?GenricDao<T,?PK>?{

private?Class<?>?entityClass;?`//?实体类的类型`

public?GenricDaoImpl()?{

entityClass?=?(Class<?>)((ParameterizedType)?(`this`.getClass()

.getGenericSuperclass())).getActualTypeArguments()[`0`];

}

}

Java code?

1

2

Type?type?=?`this`.getClass().getGenericSuperclass();

ParameterizedType?parameterizedType?=?(ParameterizedType)type;

其中ParameterizedType接口是Type的子接口,Class类是Type实现类;

但是Class类并没有实现ParameterizedType接口,强转为什么没有报错;

Class类也没有重写getActualTypeArguments()方法;

我自写了一个类似的Demo,报了com.itany.C?cannot?be?cast?to?com.itany.B,代码如下:

Java code?

1

2

3

4

5

6

7

8

9

interface?A{}

interface?B?`extends?A{}`

class?C?`implements?A{}`

public?class?Main?{

public?static?void?main(String[]?args)?{

A?a=?`new?C();`

B?b=(B)a;

}

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...