小编iro*_*oma的帖子

避免在具有多种值类型的地图中取消选中分配?

我在Java 7中遇到警告时遇到问题:

Unchecked assignment: 'java.lang.Class' to 'java.lang.Class<T>'
Run Code Online (Sandbox Code Playgroud)

我正在Class<T> type = typeMap.get(key);下面的get函数中找到它.

基本上我在这里尝试做的是我想存储一堆未知类型的键/值对(但是所有都是Object的后代,除了null),但不会丢失类型.所以我使用泛型创建了一个包含以下内容的类.它有两个映射(一个用于存储数据,另一个用于存储类类型:

    private Map<String, Object>  dataMap = new HashMap<>();
    private Map<String, Class> typeMap = new HashMap<>();

    public  <T> void put(String key, T instance){
        dataMap.put(key, instance);
        if (instance == null){
            typeMap.put(key,null);
        }
        else {
            typeMap.put(key, instance.getClass());
        }
    }

    public <T> T get(String key){
        Class<T> type = typeMap.get(key);
        if (type == null){
            return null;
        }
        return type.cast(dataMap.get(key));
    }
Run Code Online (Sandbox Code Playgroud)

它运行得很好,但警告让我烦恼.有没有办法让Java在没有抱怨的情况下进行此演员(除了抑制它)?还是有更好的方法来完成我想要做的事情?在Java 8中怎么样,因为我还没有真正有机会潜入它呢?

谢谢!

java generics casting

29
推荐指数
1
解决办法
5万
查看次数

Spring Boot REST服务:JSON反序列化不起作用

我正在使用spring-boot和Kotlin开发REST服务.(我应该提到这是我第一次使用它们.)我无法使用此代码让Jackson从POST请求中反序列化JSON:

@RequestMapping("cloudservice/login/{uuid}", method = arrayOf(RequestMethod.POST))
fun login(@PathVariable(value="uuid")uuid: String, @RequestBody user: CloudServiceUser ) : ResponseEntity<CloudServiceUser> {

    val cloudServiceFactory : Class<CloudServiceFactory> = cloudServiceRepository.cloudServiceExtensions[UUID.fromString(uuid)] ?: throw InvalidPathVariableException("Invalid UUID.")
    var token : String
    try {
        token = cloudServiceFactory.newInstance().authenticationService.login(user.userId, user.password)
    } catch (e:Exception ){
        throw CloudServiceException(e.message)
    }

    return ResponseEntity(CloudServiceUser(userId=user.userId, password = "", token = token),HttpStatus.OK)
}
Run Code Online (Sandbox Code Playgroud)

用户对象很简单:

data class CloudServiceUser(val userId: String, val password:String, val token:String)
Run Code Online (Sandbox Code Playgroud)

我收到了错误

org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not construct instance of com.irotsoma.cloudbackenc.cloudservice.CloudServiceUser: no suitable constructor found, can not deserialize …
Run Code Online (Sandbox Code Playgroud)

rest jackson kotlin spring-boot

6
推荐指数
1
解决办法
6719
查看次数

标签 统计

casting ×1

generics ×1

jackson ×1

java ×1

kotlin ×1

rest ×1

spring-boot ×1