GeXiangDong

精通Java、SQL、Spring的拼写,擅长Linux、Windows的开关机

0%

泛型:WARNING: Class Type safety: Unchecked cast from ChatServerEndPoint to T 警告的解决方法

如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.test.websocket;

import javax.websocket.server.ServerEndpointConfig.Configurator;

public class ChatServerEndPointConfigurator extends Configurator {

private ChatServerEndPoint chatServer = new ChatServerEndPoint();

@Override
public <T> T getEndpointInstance(Class<T> endpointClass)
throws InstantiationException {
return (T) chatServer;
}
}

第12行会有警告 Class Type safety: Unchecked cast from ChatServerEndPoint to T
修改为:

1
2
3
4
5
6
7
8
if(endpointClass.isAssignableFrom(chatServer.getClass())){
return endpointClass.cast(chatServer);
}else{
AssertionError ae = new AssertionError("Cannot cast to " + endpointClass.getName() +
" from " + chatServer.getClass().getName());
log.error("类型不匹配", ae);
throw ae;
}

可消除警告。