Java泛型类型转换,例如<String, String>转换为<Object, Object>。

huangapple go评论84阅读模式
英文:

Java generic type conversion like <String, String> to <Object, Object>

问题

从:<Object, Object> 到:<String, String>

或者

从:<String, String> 到:<Object, Object>

&nbsp;

我在 ConcurrentKafkaListenerContainerFactory<Object, Object>ConcurrentKafkaListenerContainerFactory<String, String> 之间有这种情况。

英文:

Is there a way in java to convert type

from : &lt;Object, Object&gt;

to : &lt;String, String&gt;

or

from : &lt;String, String&gt;

to : &lt;Object, Object&gt;

&nbsp;

I have it between ConcurrentKafkaListenerContainerFactory&lt;Object, Object&gt; and ConcurrentKafkaListenerContainerFactory&lt;String, String&gt;

答案1

得分: 2

以下是翻译好的部分:

你必须使用中间的原始类型。这里有一个从 ObjectString 转换的示例。反向转换看起来是相同的。

static ConcurrentKafkaListenerContainerFactory<Object, Object> stringFactoryToObjectFactory(
        ConcurrentKafkaListenerContainerFactory<String, String> stringFactory) {
    @SuppressWarnings("rawtypes")
    ConcurrentKafkaListenerContainerFactory rawTypeFactory = stringFactory;
    @SuppressWarnings("unchecked")
    ConcurrentKafkaListenerContainerFactory<Object, Object> objectFactory = rawTypeFactory;
    return objectFactory;
}

当然,这违反了类型安全性,如果这些工厂使用不同的类型,将在运行时引发 ClassCastException

英文:

You have to use intermediate raw type. Here's an example for Object to String conversion. Reverse conversion will look identical.

static ConcurrentKafkaListenerContainerFactory&lt;Object, Object&gt; stringFactoryToObjectFactory(
        ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; stringFactory) {
    @SuppressWarnings(&quot;rawtypes&quot;)
    ConcurrentKafkaListenerContainerFactory rawTypeFactory = stringFactory;
    @SuppressWarnings(&quot;unchecked&quot;)
    ConcurrentKafkaListenerContainerFactory&lt;Object, Object&gt; objectFactory = rawTypeFactory;
    return objectFactory;
}

Of course it violates type safety and ClassCastException will occur at runtime, if those factories will use different types.

huangapple
  • 本文由 发表于 2020年4月8日 09:08:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/61091806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定