[英]Simplest way to cast a Class<T> to a Class<E extends Enum<E>> without losing type information
我有一个方法createFoo()
创建的实例Foo<T>
使用Class<T>
实例为T
。 现在我想扩展该方法以将使用枚举类型进行的调用转发给方法createEnumFoo()
。 从第一个方法调用第二个方法似乎是非平凡的。 下面是我如何设法使用两个未经检查的强制转换和一个额外的方法,我想摆脱所有这些的例子。
方法castEnumType()
是必需的,因为我找不到将Class<?>
castEnumType()
转换为Class<E extends Enum<E>>
而不将E
绑定到某处的方法。 这涉及一个未经检查的强制转换,因为我还没有找到使用Class.asSubclass()
。 在创建Foo
实例之后,我需要将它从Foo<E>
为Foo<T>
事件,尽管E
和T
将始终是相同的类型。
我无法削弱createEnumFoo()
的签名,因为它调用Enum.valueOf(enumType, ...)
并要求其结果为E
类型。
final class Example {
<E extends Enum<E>> Foo<E> createEnumFoo(Class<E> enumType) {
// This makes use of e.g. Enum.valueOf(enumType, ...).
return null;
}
<E extends Enum<E>> Class<E> castEnumType(Class<?> enumType) {
return (Class<E>) enumType;
}
<T> Foo<T> createFoo(Class<T> type) {
if (Enum.class.isAssignableFrom(type))
return (Foo<T>) createEnumFoo(castEnumType(type));
else
// Here we would do something else or maybe throw an exception.
return null;
}
interface Foo<T> {
}
}
有更简单的方法吗?
为了澄清我面临的问题,我将解释这个问题是如何在我正在进行的项目中出现的:
在遇到此问题的代码中, Foo<T>
实际上是Converter<T>
,它是一个接口,它允许将T
实例序列化并反序列化为JSON值:
public interface Converter<T> {
JsonObject encode(T value);
T decode(JsonObject data);
}
而createFoo()
实际上是一个方法converterForType()
,它接受一个Class<T>
实例并动态调度到一堆静态方法和字段,这些方法和字段创建/包含特定于项目的常见Java类型和类型的转换器。 通常,当需要转换器时,直接访问适当的方法/字段,但有些地方只在运行时知道类型,这是使用converterForType()
地方。
现在我想扩展该方法,通过将枚举类型转换为包含枚举常量名称的JSON字符串来自动处理枚举类型。 这就是我需要从converterForType()
调用方法enumConverter()
converterForType()
。 这是enumConverter()
的实现:
public static <E extends Enum<E>> Converter<E> enumConverter(final Class<E> enumClass) {
return new Converter<E>() {
public JsonObject encode(E value) {
return Json.convert(value.name());
}
public E decode(JsonObject data) {
return Enum.valueOf(enumClass, data.asString());
}
};
}
那么,使用createEnumFoo方法的原始类型
编辑:@Feuermurmel在评论中报告的修复编译错误
@SuppressWarnings({ "unchecked", "rawtypes" })
final class Example
{
<E extends Enum<E>> Foo<E> createEnumFoo(Class enumType)
{
// This makes use of e.g. Enum.valueOf(enumType, ...).
Enum x = Enum.valueOf(enumType, "x");
return (Foo<E>) x;
}
<T extends Enum> Foo<T> createFoo(Class<T> type)
{
if (Enum.class.isAssignableFrom(type))
return (Foo<T>) createEnumFoo(type);
else
// Here we would do something else or maybe throw an exception.
return null;
}
interface Foo<T>
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.