如何在java中投递到CRTP? [英] how to cast to CRTP in java?

查看:202
本文介绍了如何在java中投递到CRTP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的情况,我做一些基本的通用作业:

I have a pretty simple case where I do some basic generic assignment:

final Detail detail = field.getAnnotation(Detail.class);
final String example = detail.example();
final Class<?> type = field.getType();
if (List.class.isAssignableFrom(type))
                    ...
else if (Enum.class.isAssignableFrom(type))
    setValue(contract, field, Enum.valueOf(type, example));
else if (...)
.....

Enum.valueOf()有点难以调用,在我的情况下,错误是:

but the Enum.valueOf() is a bit difficult to call, in my case, the error is:


< java.lang.Enum中的p> valueOf(java.lang.Class,java.lang.String)不能应用于(java.lang.Class,java.lang.String)

valueOf(java.lang.Class,java.lang.String) in java.lang.Enum cannot be applied to (java.lang.Class,java.lang.String)

这是非常有道理的,因为类型是 Class< Object> 。但是由于枚举是CRTP,我找不到一种很好的方式来转换类型,使编译器变得快乐。使用原始类型 Enum.valueOf((Class)类型,示例))唯一的答案?

This makes perfectly sense since type is Class<Object>. But since Enum is CRTP, I can't find a good way to cast type to make the compiler happy. Is using the raw type Enum.valueOf((Class)type, example)) the only answer? It gives me 2 warnings instead of only one.

推荐答案

以下行将只执行一个警告:

The following line will do it with only one warning:

...
setValue( contract, field, Enum.valueOf( type.asSubclass( Enum.class ), example ) );
...

这篇关于如何在java中投递到CRTP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆